I'm trying to read from a file inside the current user's appdata folder in C#, but I'm still learning so I have this:
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();
But I don't know what t开发者_开发技巧o type to make sure it's always the current user's folder.
I might be misunderstanding your question but if you want to to get the current user appdata folder you could use this:
string appDataFolder = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
so your code might become:
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);
}
}
or even shorter:
string appDataFolder = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData
);
string filePath = Path.Combine(appDataFolder, "test.txt");
File.ReadAllLines(filePath).ToList().ForEach(Console.WriteLine);
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
Take a look at the Environment.GetFolderPath method, and the Environment.SpecialFolder enumeration. To get the current user's app data folder, you can use either:
Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData )
to get application directory for the current, roaming user. This directory is stored on the server and it's loaded onto a local system when the user logs on, orEnvironment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData )
to get the application directory for the current, non-roaming user. This directory is not shared between the computers on the network.
Also, use Path.Combine to combine your directory and the file name into a full path:
var path = Path.Combine( directory, "test.txt" );
Consider using File.ReadLines to read the lines from the file. See Remarks on the MSDN page about the differences between File.ReadLines
and File.ReadAllLines
.
foreach( var line in File.ReadLines( path ) )
{
Console.WriteLine( line );
}
精彩评论