Check if a file is in use, wait for it to finish

佐手、 提交于 2019-12-23 13:43:06

问题


I have this problem in my application:

  • Step 1 - create an file (xml) and put some content in it
  • Step 2 - a 3rd party application will open the file and get the info from the file made in step 1.
  • Step 3 - delete the file again.

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);

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");

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?

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)?


回答1:


It looks like you just need to add something like the following:

Process p = new Process();
p.StartInfo = startInfo;
p.WaitForExit();

Process.Start() starts another process but it doesn't wait for that process to finish before continuing on.




回答2:


Description

You can use the method in my sample and do a while loop.

Sample

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;
}



回答3:


Process process = Process.Start(startInfo);
process.WaitForExit(); // alteratively, you can use WaitForExit(int milliseconds)
File.Delete("Filename");  



回答4:


This is a common problem. The solution is unfortunatley try to open it and see if there's an exception.

Use the IsFileLocked(...) from here:

Is there a way to check if a file is in use?

And do something like:

while ( IsFileLocked(new FileInfo(FilePath)) ) 
{ 
    Thread.Sleep(TimeInMiliSec); 
}


来源:https://stackoverflow.com/questions/9010806/check-if-a-file-is-in-use-wait-for-it-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!