策划有一个需求,需要读取1千多个文本文件。
最开始用的最简单的readalltext
string s = System.IO.File.ReadAllText(fileName, System.Text.Encoding.UTF8);
用了两分钟才加载进来 ,这还不疯。
后来查找文档 找到了一篇文章 ,内容很详细
https://cc.davelozinski.com/c-sharp/the-fastest-way-to-read-and-process-text-files
对文件的读取有了更深的了解,但是速度还是不理想。
于是决定使用异步的方式读取 ,终于满足了需求。
System.Threading.Tasks.Task<string> task = ReadFile(fileName);
task.ContinueWith(t =>
{
string s = t.Result;
});
private async static System.Threading.Tasks.Task<string> ReadFile(string name)
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
try
{
using (System.IO.FileStream fs = System.IO.File.Open(name, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (System.IO.BufferedStream bs = new System.IO.BufferedStream(fs))
using (System.IO.StreamReader sr = new System.IO.StreamReader(bs))
{
string s;
while ((s = await sr.ReadLineAsync()) != null)
{
stringBuilder.AppendLine(s);
}
return stringBuilder.ToString();
}
}
catch (System.Exception e)
{
return "";
}
}
在这里记录一下 ,