views:

47

answers:

3

I'm trying to read from a file inside a the current users 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 to type to make sure it's always the current user.

+4  A: 

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);
Darin Dimitrov
A: 

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

Vladi Gubler
A: 

Take a look at the Environment.GetFolderPath mehtod, 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, or
  • Environment.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 );
 }
Danko Durbić