【发布时间】:2011-12-23 15:17:45
【问题描述】:
我想逐行读取文本文件。我想知道我是否在 .NET C# 范围内尽可能高效地做到这一点。
这是我目前正在尝试的:
var filestream = new System.IO.FileStream(textFilePath,
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.ReadWrite);
var file = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128);
while ((lineOfText = file.ReadLine()) != null)
{
//Do something with the lineOfText
}
【问题讨论】:
-
Fastest你的意思是从性能或开发的角度来看? -
这将在方法执行期间锁定文件。您可以使用 File.ReadAllLines 到一个数组中,然后处理该数组。
-
顺便说一句,将
filestream = new FileStream括在using()语句中,以避免锁定文件句柄时可能出现的烦人问题 -
关于封闭 FileStream 是 using() 语句,有关推荐方法请参见 StackOverflow:StackOverflow using statement filestream streamreader
-
我认为 ReadToEnd() 更快。
标签: c# .net performance file-io text-files