c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件

今需要对日志文件读取出来,显示在日志查询里,需要用到了IO流。

1、 

FileStream fs = File.OpenRead(url);
StreamReader sr = new StreamReader((System.IO.Stream)fs, System.Text.Encoding.Default);

错误提示:文件“D:Loglog20170317.txt”正由另一进程使用,因此该进程无法访问该文件。

2、

StreamReader sr = File.OpenText(url);

错误提示:错误提示:文件“D:Loglog20170317.txt”正由另一进程使用,因此该进程无法访问该文件。

3、

string textInfo = File.ReadAllText(filePath,Encoding.Default);

错误提示:错误提示:文件“D:Loglog20170317.txt”正由另一进程使用,因此该进程无法访问该文件。

4、正确读取方式

FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);

StringBuilder sb = new StringBuilder();
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine()+"<br>");
}

 

总结:

这样的情况,不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。

引用:c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件

原文地址:https://www.cnblogs.com/code1992/p/11533212.html