Check if the file is in use, wait for it to complete

I have this problem in my application:

  • Step 1 - create a file (xml) and put some content in it
  • Step 2 - a third-party application will open the file and receive information from the file taken in step 1.
  • Step 3 - delete the file again.

The first question I have is regarding 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 is executed only when it is already done? That way, I can be 100% sure that all the data is in xml before it tries to run it correctly?

The second part, where I get the error message, is here:

 Process.Start(startInfo); File.Delete("Filename"); 

What is happening now is that the file is already deleted before a third-party program has read it in its memory.

Is there a way to verify that the file is no longer in use, or to make some kind of stable way to wait?

I already found a way to use Thread.Sleep(TimeInMiliSec); but I think this is the wrong way to do this (more like a workaround)?

+4
source share
5 answers

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 does not wait for the process to complete before continuing.

+3
source

Description

You can use the method in my example and make a while loop.

Example

 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; } 
+9
source
 Process process = Process.Start(startInfo); process.WaitForExit(); // alteratively, you can use WaitForExit(int milliseconds) File.Delete("Filename"); 
+2
source

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

Use IsFileLocked (...) here:

Is there a way to check if a file is being used?

And do something like:

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

Instead, you can check if the process continues ...

  if (System.Diagnostics.Process.GetProcessesByName("notepad").Length < 1) { Console.WriteLine("The process isnt running"); } else { Console.WriteLine("The process is running..."); //Your code to delete the file } 

Perhaps you create a timer and check it every few seconds?

Hope this helps, my first post is here :-)

0
source

Source: https://habr.com/ru/post/1393054/


All Articles