Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file that's already used by another process

Tags:

c#

file

io

I have a C# app that tries to read a log file which is being written to by another app. When I try to read the file, I get IOException

"The process cannot access the file ... because it is being used by another process."

What I tried using so far are the following, but none of them fix the problem

var log = File.ReadAllText(logPath);

var stream = new FileStream(logPath, FileMode.Open);

using (var stream = File.Open(logPath, FileMode.Open))
  {

  }
like image 457
IsaacBok Avatar asked Oct 26 '25 22:10

IsaacBok


1 Answers

try this:

FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open,   FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);

while (!logFileReader.EndOfStream)
{
    string line = logFileReader.ReadLine();
    // Your code here
}

// Clean up
logFileReader.Close();
logFileStream.Close();

edited with MethodMan's suggestions

using(FileStream logFileStream = new FileStream(@"c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using(StreamReader logFileReader = new StreamReader(logFileStream))
    {
        string text = logFileReader.ReadToEnd();
        // Your code..
    }
}
like image 99
Spongebrot Avatar answered Oct 28 '25 13:10

Spongebrot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!