在userfiles文件夹中创建一个文件(C#,Windows窗体)

Nag*_*agu 9 c# file winforms

我正在尝试在Windows窗体应用程序中创建一个文本文件.它工作正常,但它在应用程序的默认位置(如在文件夹中bin)创建文本文件.但我想将创建的文本文件保存在我的用户文件文件夹中.我该怎么做?

这是我的代码:

FileInfo fileusername = new FileInfo("userinfo.txt");
StreamWriter namewriter = fileusername.CreateText();
namewriter.Write(txtUsername.Text);
namewriter.Close();
Run Code Online (Sandbox Code Playgroud)

Fre*_*örk 18

您可以使用Environment.GetFolderPath获取用户数据文件夹的路径:

string fileName = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    "userinfo.txt");
Run Code Online (Sandbox Code Playgroud)

查看Environment.SpecialFolder枚举的文档,以便找到最适合您需求的文件夹.


Fra*_*ack 7

您可以将Environment.GetFolderPath()函数与Environment.SpecialFolder枚举一起使用.

使用:

String filePath = Path.Combine(
    Evironment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
    "userinfo.txt");
Run Code Online (Sandbox Code Playgroud)

在当前用户My Documents文件夹中创建文件名.