c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件,在IO处理上遇到了无法操作的问题。

文件“C:\u_ex.log”正由另一进程使用,因此该进程无法访问该文件。

u_ex.log是一个日志文件,不定时都可能由另外的程序对它进行日志记录写入操作。

当日志文件被其他程序所占用的情况下,用下面三种方式读取情况!

string url = @"C:\inetpub\logs\LogFiles\W3SVC1\u_ex.log";

第一种:

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

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

第二种:

StreamReader sr = File.OpenText(url);

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

第三种:

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

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

正确读取。

----------------------------------------------------------------------------------------------------------

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

详细代码:

            string[] content;
string url = @"C:\inetpub\logs\LogFiles\W3SVC1\u_ex17020815.log";
using (FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
{
content = sr.ReadToEnd().Replace("\r\n", "^").Split('^');
}
}
//如果content数组值的数量为0说明读取的文件没有数据
if (content.Count() != 0)
{
for (int i = 0; i < content.Count(); i++)
{
if (i > 3)
{
Console.WriteLine(content[i]);
}
}
}

  

05-11 11:08
查看更多