在C#中读取当前用户appdata文件夹中的文件

3

我正在尝试在C#中从当前用户的应用程序数据文件夹读取文件,但我还在学习阶段,因此我的代码如下:

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

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


另外,我正在使用Microsoft Visual Studio C# 2010 Express。 - Zeenjayli
3个回答

6
我可能误解了您的问题,但如果您想获取当前用户的应用程序数据文件夹,您可以使用以下方法:
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);

1
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接