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

相关推荐
caimouse1 小时前
ReactOS 窗口系统分析(23):键盘 — keyboard.c + kbdlayout.c
c语言·开发语言·计算机外设
Emily156853598701 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
就叫_这个吧6 小时前
Java递归方法实现面包屑导航
java·开发语言
fīɡЙtīиɡ ℡6 小时前
AI 应用系统设计
java·开发语言·人工智能
csdn_aspnet8 小时前
C# 在逗号分割的字符串中判断是否包含指定字符
c#·正则·linq·string·regex·contains
今天AI了吗8 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习
宝桥南山8 小时前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
TELL5218 小时前
selenium webdriver 第二次初始化的异常
开发语言·python
动词ing9 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习9 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展