Zee*_*yli 2 c# active-directory userappdatapath readfile
我正在尝试从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();
Run Code Online (Sandbox Code Playgroud)
但我不知道输入什么以确保它始终是当前用户的文件夹.
我可能会误解你的问题,但如果你想获得当前用户appdata文件夹,你可以使用:
string appDataFolder = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
Run Code Online (Sandbox Code Playgroud)
所以你的代码可能变成:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
甚至更短:
string appDataFolder = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData
);
string filePath = Path.Combine(appDataFolder, "test.txt");
File.ReadAllLines(filePath).ToList().ForEach(Console.WriteLine);
Run Code Online (Sandbox Code Playgroud)