C# – Read log file being used by another process

cfileremote desktop

Goal

I want to press a button on my GUI and read in the seclog.log file (symantec AV log) from a remote machine and display the contents of the log to a rich text box in my application.

Things That Work

everything but reading the log file

Error Message

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

code

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


        }

Things I've Tried

File is being used by another process

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

Googling the issue

using filestreams in multiple ways

Best Answer

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


}

what i had to change

i had to create a readwrite filestream

original code

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

new code

Stream stream = File.Open(seclogPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//File.OpenRead(seclogPath1);
StreamReader streamReader = new StreamReader(stream);
Related Topic