读取另一个进程正在使用的日志文件

目标

我想按下GUI上的按钮并从远程计算机读取seclog.log文件(symantec AV日志),并将日志内容显示在我的应用程序中的富文本框中。

有用的东西

除了阅读日志文件之外的一切

错误信息

System.IO.IOException was unhandled Message=The process cannot access the file '\\HOSTNAME\C$\Program Files (x86)\Symantec\Symantec Endpoint Protection\seclog.log' because it is being used by another process. Source=mscorlib 

 //possible seclog paths String seclogPath1 = @"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log"; String seclogPath2 = @"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log"; //if seclog exists if (File.Exists(seclogPath1)) { //output.AppendText("file exists at " + seclogPath1); //var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream stream = File.OpenRead(seclogPath1); StreamReader streamReader = new StreamReader(stream); string str = streamReader.ReadToEnd(); output.AppendText(str); streamReader.Close(); stream.Close(); } 

我试过的事情

文件正由另一个进程使用

C#进程无法访问文件”’,因为它正由另一个进程使用

谷歌搜索问题

以多种方式使用文件流

 //possible seclog paths String seclogPath1 = @"\\\\" + target + "\\C$\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\seclog.log"; String seclogPath2 = @"\\\\" + target + "\\C$\\Program Files\\Symantec\\Symantec Endpoint Protection\\seclog.log"; //if seclog exists if (File.Exists(seclogPath1)) { //output.AppendText("file exists at " + seclogPath1); //var seclogContent = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //File.OpenRead(seclogPath1); StreamReader streamReader = new StreamReader(stream); string str = streamReader.ReadToEnd(); output.AppendText(str); streamReader.Close(); stream.Close(); } 

我必须改变什么

我不得不创建一个readwrite文件流

原始代码

 Stream stream = File.OpenRead(seclogPath1); StreamReader streamReader = new StreamReader(stream); 

新代码

 Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //File.OpenRead(seclogPath1); StreamReader streamReader = new StreamReader(stream); 
 using (StreamReader sr = new StreamReader(filePath, true)) { sr.Close(); //This is mandatory //Do your file operation }