简体   繁体   中英

Creating a named .txt file and subsequently writing string to it in C#

I have been tasked to build a WPF App which uses a user input form to gather information, and then save the information as string in a text file, whose name is created as a result of user input. The UI and user input are working, but the string will not save to the text file. Whenever the code is debugged it throws a "file path not supported exception".

This is the code for my writing to the file:

System.IO.File.WriteAllLines("C:\\Users\\jhump\\Desktop\\TestingApp\\"+filename+"\\", data);

Where data is a string array containing the string to be saved, and filename is the concatted name for the file to be saved as.

Thank you in advance for your help!

You need to escape \\ characters by using an extra backslash like this \\\\ . Also you can use String Literals , like @"C:\\Users\\..." instead if you don't want to use double backslashes.

string[] data = { "Some", "Thing", "Foo", "Bar" };
string filename = "foo.txt";

System.IO.File.WriteAllLines("C:\\Users\\jhump\\Desktop\\TestingApp\\" + filename, data);

You have to concat the names of the directory or either escape the \\ backslash:

...WriteAllLines(@"C:\\yourpath\\here\\filename.txt",data)

best way for the user home folder is to use special folder paths:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM