0

Is it possible to read files from a directory one file after another?

I look for something like:

while (File file = Directory.GetFile(path)) {
    //
    // Do something with file
    //
}

[UPDATE]

I already knew about GetFiles() but I'm looking for a function that return one file at a time.

EnumerateFiles() is .Net4.x, would be nice to have, but I'm using .Net2.0. Sorry, that I didn't mention.

(Tag updated)

Anuj Balan
  • 7,419
  • 23
  • 53
  • 90
Inno
  • 2,497
  • 5
  • 32
  • 42

5 Answers5

2

You can enumerate over the file names:

foreach(string fileName in Directory.EnumerateFiles(path)) {

    // Do something with fileName - using `FileInfo` or `File`

}
Oded
  • 477,625
  • 97
  • 867
  • 998
0
string[] arFiles = Directory.GetFiles(@"C:\");

foreach (var sFilename in arfiles)
{
    // Open file named sFilename for reading, do whatever
    using (StreamReader sr = File.OpenText(sFilename )) 
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) 
        {
            Console.WriteLine(s);
        }
    }
}
Shai
  • 24,239
  • 7
  • 43
  • 65
0
foreach (var file in Directory.EnumerateFiles(path))
{
    var currFileText = File.ReadAllText(file);
}
SimpleVar
  • 13,374
  • 4
  • 37
  • 60
0

What about Directory.GetFiles(path) method?

foreach(String fileName in Directory.GetFiles(path))
{
    FileInfo file = new FileInfo(fileName);
}
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
0

Try with this...

 foreach (var filePath in Directory.GetFiles(path))
            {
                var text = File.ReadAllText(filePath);
                // Further processing
            } 
bhavesh lad
  • 1,172
  • 1
  • 11
  • 23