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

相关推荐
wangnaisheng1 分钟前
【C#】死锁详解:发生原因、优化解决方案
c#
Rabitebla4 分钟前
vector 的骨架:三根指针、模板陷阱与迭代器失效的第一现场
开发语言·数据结构·c++·算法
时空系4 分钟前
第7篇:功能——打造你的工具箱 Rust中文编程
开发语言·网络·rust
csbysj202013 分钟前
CSS !important:深度解析与最佳实践
开发语言
初心未改HD18 分钟前
Go语言测试与Benchmark:测试驱动开发的实践指南
开发语言·golang
chxii25 分钟前
lua流程控制语句和table(表)数据结构
开发语言·junit·lua
逻辑驱动的ken33 分钟前
Java高频面试考点场景题20
java·开发语言·深度学习·面试·职场和发展
W.A委员会34 分钟前
多行溢出在末尾添加省略号
开发语言·javascript·css
wjs202436 分钟前
RSS Item 元素:深入解析与使用指南
开发语言
tiger从容淡定是人生38 分钟前
AI替代软件战略(一):从 CCleaner 到 MCP 架构重构 —— TigerCleaner 的工程实践
人工智能·重构·架构·c#·mcp