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

 

log20170317.txt是一个自动任务生成log4net的日志文件,自动任务一直在执行。

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

1、 

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

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

2、

StreamReader sr = File.OpenText(url);

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

3、

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

错误提示:错误提示:文件“D:\Log\log20170317.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。因为随时有其他程序对其进行写操作。

 

posted @ 2017-03-17 17:19  lappple  阅读(26719)  评论(0编辑  收藏  举报