3

我正在尝试从 C# 中当前用户的 appdata 文件夹中的文件读取,但我仍在学习,所以我有这个:

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
    counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

但我不知道输入什么来确保它始终是当前用户的文件夹。

4

3 回答 3

6

我可能误解了您的问题,但如果您想获取当前用户的 appdata 文件夹,您可以使用以下命令:

string appDataFolder = Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData);

所以你的代码可能会变成:

string appDataFolder = Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData
);
string filePath = Path.Combine(appDataFolder, "test.txt");
using (var reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

甚至更短:

string appDataFolder = Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData
);
string filePath = Path.Combine(appDataFolder, "test.txt");
File.ReadAllLines(filePath).ToList().ForEach(Console.WriteLine);
于 2010-07-14T06:18:14.760 回答
1
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
于 2010-07-14T06:19:52.880 回答
0

查看Environment.GetFolderPath方法和Environment.SpecialFolder枚举。要获取当前用户的应用数据文件夹,您可以使用:

  • Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData )获取当前漫游用户的应用程序目录。此目录存储在服务器上,并在用户登录时加载到本地系统,或者
  • Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData )获取当前非漫游用户的应用程序目录。此目录不在网络上的计算机之间共享。

此外,使用Path.Combine将您的目录和文件名组合成一个完整路径:

var path = Path.Combine( directory, "test.txt" );

考虑使用File.ReadLines从文件中读取行。有关和之间的差异,请参阅MSDN 页面上的备注。File.ReadLinesFile.ReadAllLines

 foreach( var line in File.ReadLines( path ) )
 {
     Console.WriteLine( line );
 }
于 2010-07-14T06:41:32.663 回答