检查文件是否正在使用中,等待文件完成

Dan*_*986 4 c# load file delete-file

我在我的应用程序中遇到此问题:

  • 第1步 - 创建一个文件(xml)并在其中放入一些内容
  • 第2步 - 第三方应用程序将打开该文件并从步骤1中生成的文件中获取信息.
  • 第3步 - 再次删除文件.

我的第一个问题是这部分代码:

XmlDocument xmlDoc = new XmlDocument();
DataSet ds = //use a method to put in the data
xmlDoc.LoadXml(ds.GetXml());
xmlDoc.Save("Filename");
// ...
Process.Start(startInfo);
Run Code Online (Sandbox Code Playgroud)

我的假设是否正确,只有在完成上述操作后才会执行最后一行?所以我可以100%确定数据是否都在xml中,然后才能尝试启动它?

我现在收到错误的第二部分是:

Process.Start(startInfo);
File.Delete("Filename");
Run Code Online (Sandbox Code Playgroud)

现在发生的事情是,在第三方程序将文件读​​入其内存之前,该文件已被删除.

有什么方法可以检查文件不再使用,或者做一些稳定的等待方式?

我已经找到了一种使用方法,Thread.Sleep(TimeInMiliSec);但我想这不是一种正确的方法(更像是一种解决方案)?

dkn*_*ack 9

描述

您可以在我的示例中使用该方法并执行while循环.

样品

while (IsFileLocked(new FileInfo("YourFilePath")))
{
    // do something, for example wait a second
    Thread.Sleep(TimeSpan.FromSeconds(1));
}
// file is not locked

public static bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*rvy 4

看起来您只需要添加如下内容:

Process p = new Process();
p.StartInfo = startInfo;
p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

Process.Start() 启动另一个进程,但它不会等待该进程完成后再继续。