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
  • 18,404
  • 16
  • 78
  • 126
robert woods
  • 375
  • 2
  • 7
  • 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
  • 97,193
  • 102
  • 206
  • 364
1

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
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,640
  • 1
  • 34
  • 50