3

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.

76484
  • 8,498
  • 3
  • 19
  • 30
Zeenjayli
  • 119
  • 2
  • 3
  • 14

3 Answers3

6

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Vladi Gubler
  • 2,458
  • 1
  • 13
  • 15
0

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 );
 }
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Danko Durbić
  • 7,077
  • 5
  • 34
  • 39