1

Possible Duplicate:
how to read all files inside particular folder

I have the following code which I came up with:

string[] lines = System.IO.File.ReadAllLines(@"C:\Notes\Variables1.txt");
foreach (string line in lines)
{
   process(line);
}

string[] lines = System.IO.File.ReadAllLines(@"C:\Notes\test1.txt");
foreach (string line in lines)
{
   process(line);
}

Is there a simple and reliable way that I can modify the code so that it looks up all the .txt files in my Notes directory and then reads each one in turn. Some way I can code this up without having to specify each file in turn and something that won't crash if the file is empty.

Community
  • 1
  • 1
Jason
  • 239
  • 1
  • 2
  • 5

6 Answers6

4
string[] files = Directory.GetFiles(source, "*.txt");
foreach(string filename in files) 
{
   //go do something with the file
}
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
JonH
  • 32,732
  • 12
  • 87
  • 145
2

Use the DirectoryInfo class to get a listing of all files.

Is has an overloaded EnumerateFiles method, just for this.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

You can get a collection of the files in any given directory using Directory.GetFiles(). Then just process them one by one like you were already doing.

string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)
{
    string[] lines = File.ReadAllLines(file);
    foreach (string line in lines)
    {
        process(line);
    }        
}

There's a lot more in the System.IO namespace.

hunter
  • 62,308
  • 19
  • 113
  • 113
  • Thanks. By the way is there some way I can get the filename and put it into a string? – Jason Aug 09 '11 at 13:40
  • 1
    @Jason: It's already in the `string file`. If you need to strip away the extension, path, etc. you should fill this string into a [`FileInfo`](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx) or use the static methods of the [`Path`](http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx) class. – Oliver Aug 09 '11 at 13:45
0
string[] files = Directory.GetFiles(directory);
foreach(string filename in files)
{
   if (Path.GetExtension(filename) != ".txt")
      continue;

   string[] lines = System.IO.File.ReadAllLines(filename);
   foreach (string line in lines)
   {
      process(line);
   }
}
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
0

Use System.IO.Directory.ReadFiles

For example:

string[] filePaths = Directory.GetFiles(@"c:\Notes\", "*.txt")

Then simply iterate through the file paths

Steve Mallam
  • 456
  • 2
  • 6
0

You want:

Directory.GetFiles(path, "*.txt");

This will return an array of names so you can loop over each file in turn:

foreach (string file in Directory.GetFiles(path, "*.txt"))
{
    string[] lines = System.IO.File.ReadAllLines(file);
    foreach (string line in lines)
    {
        process(line);
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325