C# 读取另一个进程使用的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9759697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:45:00  来源:igfitidea点击:

Reading a file used by another process

c#file-iofile-locking

提问by Christoffer

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 Streamreaderon the file as it is being used by another process. Setting up a Filestreamwith ReadWritewon't do any good since I cannot control the process that is using the file.

问题是我不能Streamreader在文件上使用used by another process. 设置FilestreamwithReadWrite不会有任何好处,因为我无法控制使用该文件的过程。

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.
  1. 监控文件
  2. 当它发生变化时制作它的临时副本
  3. 阅读临时副本
  4. 删除临时副本。

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

每当服务器更改文件时,我都需要获取文件中的文本。

采纳答案by Hans Passant

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.

如果记事本可以读取文件,那么您也可以,显然程序没有对文件设置读取锁定。您遇到的问题是 StreamReader 将使用 FileShare.Read 打开文件。拒绝写访问。那不行,另一个程序已经获得了写权限。

You'll need to create the StreamReader like this:

您需要像这样创建 StreamReader:

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.

猜测这里的编码。你必须小心这种代码,另一个程序正在积极地写入文件。你不会得到一个非常可靠的文件结束指示,得到部分最后一行是很有可能的。当您继续阅读文件以尝试获取附加的程序时尤其麻烦。

回答by SLaks

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.

只要其他应用程序没有以独占方式锁定文件,这应该有效。