Zeenjayli
Zeenjayli

Reputation: 119

Reading from a File in current User appdata folder for C#

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 to type to make sure it's always the current user's folder.

Upvotes: 3

Views: 6880

Answers (3)

Danko Durbić
Danko Durbić

Reputation: 7237

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

Upvotes: 0

Vladi Gubler
Vladi Gubler

Reputation: 2458

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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

Upvotes: 6

Related Questions