从文件夹使用流读取器读取文件在c#
问题描述:
有没有什么办法可以连接到文件夹,然后使用streamreader一个接一个地读取文件(包含文件的文件夹在同一台机器上),我不想直接提供文件路径在streamreader中,而我想提供文件夹的路径或位置,我的文件保存完成后,我想打开一个循环并逐个读取所有文件。从文件夹使用流读取器读取文件在c#
目前我正在尝试下面的代码,但我必须提供文件名以及我不想要的路径。
StreamReader sr = new StreamReader(path);
请提出这方面的任何最优解,
感谢 yogendra
答
您可以使用Directory.GetFiles http://msdn.microsoft.com/en-us/library/07wt70x2.aspx
var FileList = Directory.GetFiles(DirectoryPath);
foreach (var file in FileList)
{
StreamReader sr = new StreamReader(file);
// Do some work
}
答
事情是这样的:
更多信息可以发现h ERE http://msdn.microsoft.com/en-us/library/system.io.fileinfo.opentext.aspx
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\SomeFolder\");
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.IO.FileInfo fi in di.GetFiles())
{
using (System.IO.StreamReader reader = fi.OpenText())
{
sb.AppendLine(reader.ReadToEnd());
}
}
http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx - 通过文件只是循环。 –
您在发布之前是否尝试过Google? – Tamir
http://www.csharp-examples.net/get-files-from-directory/ – sashkello