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

相关推荐
asdfg125896339 分钟前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
dsyyyyy11011 小时前
JavaScript变量
开发语言·javascript·ecmascript
z落落2 小时前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway22 小时前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446232 小时前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了2 小时前
安装git bash选项推荐
开发语言·git·bash
ct9783 小时前
React 状态管理方案深度对比
开发语言·前端·react
数量技术宅3 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦3 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai
huangdong_3 小时前
电商商品SKU图自动分类技术实现:从DOM解析到智能归档
开发语言