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,629
  • 23
  • 58
  • 92
Inno
  • 2,567
  • 5
  • 32
  • 44

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
  • 489,969
  • 99
  • 883
  • 1,009
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
  • 25,159
  • 9
  • 44
  • 67
0
foreach (var file in Directory.EnumerateFiles(path))
{
    var currFileText = File.ReadAllText(file);
}
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
0

What about Directory.GetFiles(path) method?

foreach(String fileName in Directory.GetFiles(path))
{
    FileInfo file = new FileInfo(fileName);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Try with this...

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