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

时间:2012-10-17 20:20:25

标签: c# file remote-desktop

目标

我想按下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();


        }

我尝试过的事情

File is being used by another process

C# The process cannot access the file ''' because it is being used by another process

Google搜索问题

以多种方式使用文件流

2 个答案:

答案 0 :(得分:32)

//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 filestream

原始代码

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);

答案 1 :(得分:1)

using (StreamReader sr = new StreamReader(filePath, true))
{
   sr.Close(); //This is mandatory
   //Do your file operation
}