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

相关推荐
HelloRevit8 分钟前
Windows Server SMB 共享文件 回收站
windows·c#
写代码的【黑咖啡】13 分钟前
Python 中的 Requests 库:轻松进行 HTTP 请求
开发语言·python·http
BD_Marathon13 分钟前
MyBatis各种查询功能
java·开发语言·mybatis
研☆香15 分钟前
JavaScript 特点介绍
开发语言·javascript·ecmascript
Howrun77717 分钟前
虚幻引擎_AController_APlayerController_AAIController
开发语言·c++·游戏引擎·虚幻
曹牧24 分钟前
C#:ToDouble
开发语言·c#
袁袁袁袁满27 分钟前
Python读取doc文件打印内容
开发语言·python·python读取doc文件
zcfeng53039 分钟前
PHP升级
开发语言·php
m0_7482523842 分钟前
Ruby 模块(Module)的基本概念
开发语言·python·ruby
羊小猪~~1 小时前
【QT】-- QT基础类
开发语言·c++·后端·stm32·单片机·qt