robert woods
robert woods

Reputation: 375

Read all text files in a folder with StreamReader

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")))

Upvotes: 3

Views: 26412

Answers (3)

gustavodidomenico
gustavodidomenico

Reputation: 4681

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?

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98750

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)
{
   ...
}

Upvotes: 9

SLaks
SLaks

Reputation: 887479

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

Upvotes: 0

Related Questions