Frustrated Guy Frustrated Guy - 1 year ago 64 Question

How can I read a file even when getting an "in use by another process" exception?

In VB.NET or C#, I'm trying to read the contents of a text file that is in use by another program (that's the point, actually, I can't stop the program or it stops writing to the text file, and I want to periodically read out what is currently in the text file in another program).

This is the code I'm using (VB.NET)

Dim strContents As String
Dim objReader As StreamReader
objReader = New StreamReader(FullPath)
strContents = objReader.ReadToEnd()

Or in C#:

var objReader = new StreamReader(FullPath);
var strContents = objReader.ReadToEnd();

The above, however, throws the IO exception "The process cannot access the file 'file.txt' because it is being used by another process." Are there any workarounds in this scenario?

Answer Source
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

Original source for code