检查文件是否正在使用中,等待其完成 [英] Check if a file is in use, wait for it to finish
问题描述
我的应用程序中存在此问题:
I have this problem in my application:
- 第1步-创建文件(xml)并将一些内容放入其中
- 第2步-第三方应用程序将打开文件并从第1步中创建的文件中获取信息。
- 第3步-再次删除文件。
我遇到的第一个问题是关于代码的这一部分:
The first question that I have is about this part of the code:
XmlDocument xmlDoc = new XmlDocument();
DataSet ds = //use a method to put in the data
xmlDoc.LoadXml(ds.GetXml());
xmlDoc.Save("Filename");
// ...
Process.Start(startInfo);
我的假设是否正确,即只有在完成上述操作后才执行最后一行?
所以我可以100%确保数据全部包含在xml中,然后再尝试正确启动它?
Is my assumption correct that the last line only gets executed when the above is already done? So I can be 100% sure that the data is all in the xml before it tries to start it right?
第二部分出现错误现在在这里:
The second part where I get an error now is here:
Process.Start(startInfo);
File.Delete("Filename");
现在发生的情况是,在第3方程序将文件读入文件之前,该文件已被删除内存。
What happens now, is that the file already gets deleted before the 3rd party program had read it into its memory.
是否可以通过某种方式检查文件是否不再使用,或者采取某种稳定的等待方式?
Is there some way that I can check that the file is no longer in use, or make some stable way of waiting?
我已经找到了一种使用 Thread.Sleep(TimeInMiliSec);
的方法,但是我想这不是正确的方法(更像是解决方法)?
I already found a way to use Thread.Sleep(TimeInMiliSec);
but I guess this is not a correct way of doing this (more like a workaround solution)?
推荐答案
看起来您只需要添加以下内容:
It looks like you just need to add something like the following:
Process p = new Process();
p.StartInfo = startInfo;
p.WaitForExit();
Process.Start()启动另一个进程,但它不等待该进程完成再继续上。
Process.Start() starts another process but it doesn't wait for that process to finish before continuing on.
这篇关于检查文件是否正在使用中,等待其完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!