C# File.ReadAllLines()报错

项目中需要读取一个文本文件的内容,调用C#的File.ReadAllLines(path)方法,但是报错,就提示unknown exception,也没其他提示了。

文件是在的,并且,如果把文件拷贝到另外一个路径,再次读取是正常的。

仔细研究了一下,应该是客户电脑上跑了其他程序正在往这个文件里写东西,把文件lock了,导致ReadAllLines()方法读不了。

网上查到了解决办法:

cs 复制代码
public static string[] readAllLines(String i_FileNameAndPath)
{
     string[] o_Lines = null;
     List<string> list = new List<string>();
     int i = 0;
     using (FileStream fileStream = File.Open(i_FileNameAndPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
          using (StreamReader streamReader = new StreamReader(fileStream))
          {
              while (streamReader.Peek() > -1)
              {
                  string line = streamReader.ReadLine();     
                  list.Add(line);
                  i++;
              }
          }
      }
      o_Lines = list.ToArray();
      return o_Lines;
}

参考:C# -- Can't read all lines in file that being used by another process -- iTecNote

相关推荐
黄河滴滴22 分钟前
java系统变卡变慢的原因是什么?从oom的角度分析
java·开发语言
老华带你飞40 分钟前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
superman超哥1 小时前
Rust Workspace 多项目管理:单体仓库的优雅组织
开发语言·rust·多项目管理·rust workspace·单体仓库
kylezhao20191 小时前
C#通过HSLCommunication库操作PLC用法
开发语言·c#
JIngJaneIL2 小时前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
期待のcode2 小时前
Java的抽象类和接口
java·开发语言
wadesir2 小时前
Go语言中高效读取数据(详解io包的ReadAll函数用法)
开发语言·后端·golang
小高不明3 小时前
前缀和一维/二维-复习篇
开发语言·算法
龘龍龙3 小时前
Python基础(八)
开发语言·python
幺零九零零4 小时前
Golang-Swagger
开发语言·后端·golang