开发者

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

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");


Just add the path to the filename, like FileInfo fileusername = new FileInfo(@"c:\Users\MyUser\Documents\userinfo.txt");


String path = Environment.GetFolderPath( Environment.SpecialFolder.Personal );

OR

String path = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments );


From the looks of it you simply want to create your text file in a custom directory. My advice would be to create a constant for the path (perhaps saving it in the app.config file).

<appSettings>
    <add key="UserInfo" value="/Settings/UserInfo.txt" /> 
</appSettings>

Use a relative path to your exe so regardless of where you install your application the settings will always be saved to "PathToExe/Settings/UserInfo.txt".

Then you would do something like:

string UserInfoPath = ConfigurationManager.AppSettings["UserInfo"];
if (String.IsNullOrEmpty(UserInfoPath))
{
    // perhaps use a default value or raise an exception
}

FileInfo fileusername = new FileInfo(Path.Combine(Application.StartUpPath, UserInfoPath));
StreamWriter namewriter = fileusername.CreateText();
namewriter.Write(txtUsername.Text);
namewriter.Close();

However, you may come across a permissions issues using this approach, it is usually a better idea to store things like this either in the Registry or in the AppData directory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜