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()
objReader.Close()
Or in C#:
var objReader = new StreamReader(FullPath);
var strContents = objReader.ReadToEnd();
objReader.Close();
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?
Original source for code
Not sure how this will behave with an already open file, but this will prevent your application from locking it:
Hope it helps!
It depends on the
FileShare
mode with which the file was opened by the other application that is appending to the file. When the other application was opening the file, it specified aFileShare
mode for other applications to access the file. ThisFileShare
mode could have been read, write, both, delete, all of these, or none.You have to specify the very same
FileShare
mode that the other application specified. If the other application allowed only reading, useFileShare.Read;
if it allowed both reading and writing, useFileShare.ReadWrite
.StreamReader
uses onlyFileShare.Read
mode, so you can already assume that that's not the right one. So, try ReadWrite, like so:I'll do the fish. The FileShare mode is critical, you must allow for write sharing. That cannot be denied since the process that is writing the file already obtained write access. The StreamReader() constructor uses FileShare.Read and doesn't have an option to use a different value. Using the StreamReader(Stream) constructor is instead is indeed the workaround.
Beware however that this sharing mode also has implications for your code. You cannot predict when the other process flushes the file. The last line you read may contain only part of a line of text. When it flushes is file buffer again, later, you'll get the rest of the line. Clearly this can mess up your logic.