I have this problem in my application:
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)?
You can use the method in my sample and do a while loop.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With