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

相关推荐
唐青枫7 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech16 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf2 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6252 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0063 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术3 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园3 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob3 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享3 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm