I'm trying to create a text file in my Windows Forms application. It is working fine, but it is creating the text file in the application's default location (like in folder bin
). But I want to save that created text file in my user files folder. How can I do it?
This is my code:
FileInfo fileusername = new FileInfo("userinfo.txt");
StreamWriter namewriter = fileusername.CreateText();
namewriter.Write(txtUsername.Text);
namewriter.Close();
You can use Environment.GetFolderPath
to get the path to the user data folder:
string fileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"userinfo.txt");
Look into the documentation of the Environment.SpecialFolder enum in order to find the folder that best suits your needs.
You can use the Environment.GetFolderPath() function together with the Environment.SpecialFolder
enumeration.
Use:
String filePath = Path.Combine(
Evironment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"userinfo.txt");
to create the file name in the current users My Documents
folder.
You can use Environment.SpecialFolder to create a filepath that points to my documents:
string filePath = System.IO.Path.Combine(Environment.SpecialFolder.ApplicationData.ToString(), "userinfo.txt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With