读出由另一过程中使用的文件 [英] Reading a file used by another process

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

问题描述

我监测正在由服务器程序写入到文本文件中。每个文件被更改的内容时会输出到一个窗口,在我的程序。

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 上的文件,因为它正在使用另一个进程。建立一个文件流读写将没有任何好处,因为我无法控制正在使用该文件的进程。

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
    //...
}

在这里的编码猜测。你必须要小心这种code,其他程序正在积极地写入文件。你不会得到一个非常可靠的档案结尾指示,让部分最后一行是完全可能的。特别麻烦,当你不断读取文件,试图得到任何程序追加。

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天全站免登陆