Frustrated Guy Frustrated Guy - 1 year ago 62
C# Question

Overwrite text file that is in use by another process?

I have a log file that is open and in use by another program, and I read it's contents with the following:

Dim strContents As String
Dim x As New FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim objReader As StreamReader
objReader = New StreamReader(x)
strContents = objReader.ReadToEnd()

This works for reading the text from the file while it is still in use by the other program, however, immediately after this I need to truncate the text file (without deleting it) so that it is blank again. But the file will still be in use by the other program.

I tried

Dim sWrite As StreamWriter
sWrite = New System.IO.StreamWriter(FullPath, False)

But I get the "in use by another application" exception. I've tried looking in StackOverflow and googling but I can't seem to find an answer, and I can't find a way to do this with filestreams either, or I would try to use

Dim fs As New FileStream(FullPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)

Thanks in advance.

Answer Source

There are a fair few other posts on this topic.

Detecting whether a file is locked by another process (or indeed the same process)

How to check For File Lock in C# ?

Can I simply 'read' a file that is in use?

The solution appears to be:

'Code to read file if its not locked by another app
Catch as System.IO.IOException

Also just an FYI that your log file is unmanaged resource so deterministic finalization will help with this resource contention issue. Use the Using statement for deterministic finalization, eg:

Using fs = New FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
End Using