Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file in the userfiles folder (C#, Windows Forms)

Tags:

c#

file

winforms

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();
like image 991
Nagu Avatar asked Oct 12 '09 07:10

Nagu


3 Answers

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.

like image 107
Fredrik Mörk Avatar answered Sep 22 '22 14:09

Fredrik Mörk


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.

like image 34
Frank Bollack Avatar answered Sep 21 '22 14:09

Frank Bollack


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");
like image 26
Christian Avatar answered Sep 20 '22 14:09

Christian