2

I am trying to read all .txt files in a folder using stream reader. I have this now and it works fine for one file but I need to read all files in the folder. This is what I have so far. Any suggestions would be greatly appreciated.

using (var reader = new StreamReader(File.OpenRead(@"C:\ftp\inbox\test.txt")))
Otiel
  • 17,975
  • 14
  • 74
  • 124
robert woods
  • 375
  • 2
  • 6
  • 20
  • 2
    possible duplicate of [how to read all files inside particular folder](http://stackoverflow.com/questions/5840443/how-to-read-all-files-inside-particular-folder) – Otiel Jan 31 '13 at 16:22
  • -1 - I fail to see how this includes any research effort. – Austin Salonen Jan 31 '13 at 16:33

3 Answers3

8

You can use Directory.EnumerateFiles() method instead of.

Returns an enumerable collection of file names that match a search pattern in a specified path.

var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt");
foreach (string currentFile in txtFiles)
{
   ...
}
Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
1

You can call Directory.EnumerateFiles() to find all files in a folder.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
1

You can retrieve the files of a directory:

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

Therefore you can iterate each file performing whatever you want. Ex: reading all lines.

And also you can use a file mask as a second argument for the GetFiles method.

Edit:

Inside this post you can see the difference between EnumerateFiles and GetFiles.

What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?

Community
  • 1
  • 1
gustavodidomenico
  • 4,579
  • 1
  • 33
  • 50