c# - 打开文件和读取内容的最可靠方法是什么

标签 c# .net performance

<分区>

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

using (var fileStream = File.OpenRead(...))
  using (var reader = new StreamReader(fileStream))
     var content = reader.ReadToEnd();

有更好/更快的方法吗?

最佳答案

string content = System.IO.File.ReadAllText(@"your file path");

如果你想获取行数:

string[] lines = System.IO.File.ReadAllLines(@"your file path");

如果您只想读取行直到到达某行,则使用 IEnumerable ReadLines:

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

关于c# - 打开文件和读取内容的最可靠方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803945/

相关文章:

c# - 在 C# 中对撇号字符串执行 Newtonsoft JSON 反序列化时出错

c# - 如何在 C# 中实现 sdbm 哈希函数?

.net - 删除 IIS express 上的 30MB 上传限制

python - 为什么在 `reversed` 字符串中搜索更大的字符串比切片反转花费更多的时间?

C# 使用 Ajax 在登录到 Azure AD 后从后端获取数据

ASP.NET MVC 条件 ViewModel 抽象

.net - 执行堆栈不足异常

c++ - 从派生指针调用虚函数而不支付 vtable 价格

performance - 在函数运行时测量函数完成的时间

c# - 绑定(bind)到 BindingList 的 DataGridView 显示空行