Reading a file used by another process [duplicate]

安稳与你 提交于 2019-12-17 03:36:25

问题


I am monitoring a text file that is being written to by a server program. Every time the file is changed the content will be outputted to a window in my program.

The problem is that I can't use the Streamreader on the file as it is being used by another process. Setting up a Filestream with ReadWrite won't do any good since I cannot control the process that is using the file.

I can open the file in notepad. It must be possible to access it even though the server is using it.

Is there a good way around this?

Should I do the following?

  1. Monitor the file
  2. Make a temp copy of it when it changes
  3. Read the temp copy
  4. Delete the temp copy.

I need to get the text in the file whenever the server changes it.


回答1:


If notepad can read the file then so can you, clearly the program didn't put a read lock on the file. The problem you're running into is that StreamReader will open the file with FileShare.Read. Which denies write access. That can't work, the other program already gained write access.

You'll need to create the StreamReader like this:

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default)) {
    // read the stream
    //...
}

Guessing at the Encoding here. You have to be careful with this kind of code, the other program is actively writing to the file. You won't get a very reliable end-of-file indication, getting a partial last line is quite possible. In particular troublesome when you keep reading the file to try to get whatever the program appended.




回答2:


Call

File.Open(path, FileMode.Read, FileAccess.Read, FileShare.ReadWrite)

This should work as long as the other application has not locked the file exclusively.



来源:https://stackoverflow.com/questions/9759697/reading-a-file-used-by-another-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!