打开文件和阅读内容最有效的方法是什么

oaz*_*bir 3 .net c# performance

当我必须始终阅读整个文件时,我通常会这样做:

using (var fileStream = File.OpenRead(...))
  using (var reader = new StreamReader(fileStream))
     var content = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

有更好/更快的方式吗?

Jal*_*aid 7

string content = System.IO.File.ReadAllText(@"your file path");
Run Code Online (Sandbox Code Playgroud)

如果你想获得线条:

string[] lines = System.IO.File.ReadAllLines(@"your file path");
Run Code Online (Sandbox Code Playgroud)

如果你想只读取行直到找到某行,那么使用IEnumerable ReadLines:

foreach(string line in System.IO.File.ReadLines(@"your file path")
{
    if (line == ...)
    {
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)