开发者

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()
    objReader.Close()

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)
    sWrite.Write("")
    sWrite.Close()

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, Fil开发者_如何学运维eShare.ReadWrite)

Thanks in advance.


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?

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

The solution appears to be:

Try
'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)
    fs.SetLength(0)
    file.Save(fs)
    fs.Flush()
End Using


Thats because the other program has a lock on the file the operating system won't let you do what you want to do. Unless you change the other program to no lock on write.


Unfortunately, the solution to the problem is not as simple adding or modifying a few lines code, regardless of the language being used. You are describing a classic example of resource contention.

This type of problem is best solved using an access manager, i.e. another process that arbitrates writes such that your program doesn't overwrite what the other program did and vice versa.


I'm not sure if you can do that until the other process closes the stream. However, you can kill the process that is writing to the file.

Here's an example to do that.

Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")

For Each p As Process In pProcess
    p.Kill()
Next

Check this out: http://vbnetsample.blogspot.com/2007/08/start-and-kill-process.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜