简体   繁体   English

读取C#编写的XML文件

[英]Reading XML file as it is written C#

I have a program that logs it's progress and other data to an XML file. 我有一个程序可以将进度和其他数据记录到XML文件中。 I want to be able to open this XML file without blocking out the writer program (not a .NET program, and I have no control over it), and to read the XML as it comes, waiting for more when it is all processed, until the EOF is received. 我希望能够在不阻止编写器程序(不是.NET程序,而且我无法控制它)的情况下打开此XML文件,并读取XML,以便在处理完所有内容后等待更多,直到收到EOF。

How can this be achieved in C#? 如何在C#中实现?

Note that there are 2 problems: 请注意有两个问题:

  1. Keeping a reading stream open without blocking the other process. 保持阅读流畅通无阻。
  2. Knowing when there is more input and waiting when there isn't. 知道何时有更多输入,等什么时候没有输入。

If I needed to do this I would do something like the following: 如果需要这样做,我将执行以下操作:

Use a FileSystemWatcher to get notified when the file changes. 使用FileSystemWatcher在文件更改时得到通知。 Then just read the file and parse the XML as you require. 然后,只需读取文件并根据需要解析XML。

I would go down this route as it will be difficult to read the stream as and when the external application writes to the file. 我会走这条路,因为当外部应用程序写入文件时,很难读取流。

I did soemthing similar in past yielding in an OS program called Tailf . 我以前在名为Tailf的OS程序中做了类似的事情 Just check the code if you want to do it yourself, or grab all from it, it should almost work for you as well, a part the fact I just care about text files. 只是检查代码,如果您想自己做,或者从中获取所有内容,它也几乎同样适用于您,部分原因是我只关心文本文件。

You can open a file stream without locking it by passing in the following flags: 您可以通过传递以下标志来打开文件流而不锁定它:

new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

As far as waiting for the "EOF", if the other program is only writing data intermittently, you may have to put some sort of heuristics into your progress (ie. stop peeking for new data only if there's nothing new for X minutes). 至于等待“ EOF”,如果另一个程序只是间歇性地写入数据,则您可能不得不对进度进行某种启发式操作(即,只有在X分钟内没有新内容时才停止查看新数据)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM