读取另一个进程使用的文件 [英] Reading a file used by another process

查看:23
本文介绍了读取另一个进程使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在监视服务器程序正在写入的文本文件.每次更改文件时,内容都会输出到我程序中的一个窗口中.

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.

问题是我不能在文件上使用 Streamreader,因为它正被另一个进程使用.使用 ReadWrite 设置 Filestream 不会有任何好处,因为我无法控制正在使用该文件的进程.

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?

我应该做以下事情吗?

  1. 监控文件
  2. 当它发生变化时制作一个临时副本
  3. 阅读临时副本
  4. 删除临时副本.

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

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

推荐答案

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

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:

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.

这篇关于读取另一个进程使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆