Reputation: 375
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
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
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
Reputation: 887479
You can call Directory.EnumerateFiles()
to find all files in a folder.
Upvotes: 0