4

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

  }
IsaacBok
  • 424
  • 5
  • 18

2 Answers2

4

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..
    }
}
Glen Little
  • 6,951
  • 4
  • 46
  • 68
Spongebrot
  • 211
  • 1
  • 9
  • 1
    I would wrap the code around a using to handle the auto dipsosing of the FileStream and StreamReader Objects just a suggestion. also `"c:\test.txt"` should be `@"c:\test.txt"` to avoid the compiler seeing the single backslash as an escape character.. – MethodMan Apr 11 '16 at 21:59
  • You can also use the ReadToEnd method of the StreamReader instead of reading lines one at time to shorten your code. – Fabien ESCOFFIER Apr 11 '16 at 22:07
-1

You can do nothing, if the "another app" does not use Share.Read while creating/opening the file.

Sergei Zinovyev
  • 1,238
  • 14
  • 14