1

I am creating a file using a PDFCreator command line using Processand start(). I wait for a sometime using WaitForExit() else I Kill the process and use WaitForExit() again.

After these steps sometimes the output file is created and sometimes not. So I check if the File.Exist() and access the output file.

The issue I am facing is that even though the process creating the file is either killed or returned , sometimes this file is being used by another Process (probably some other process created by PDFCreator or a Spooler I am not sure)

So I Wait() for 3 seconds and poll again for x number of tries, then throw my exception for a failure.

I need to move the created files, and I need to check that if the file exists, then wait until the other process using it releases it or (probably find which process is using it and kill it?). If the file does not exit, I can just proceed for failure case.

How to go about it?

I can probably try to move, then if an exception for another process is using it then I can poll and wait.

But any clean way approach? I am not sure why the file is in use even after the Process has been killed or returned.

Dexters
  • 2,419
  • 6
  • 37
  • 57

1 Answers1

0

Your root issues is probably the fact that you are using "kill" on your creation process before it has completed its task. Ideally you should wait for completion before proceeding or you will experience lockouts like you are getting now.

That said in order to check if the file is in use and available to be moved you can try using this code taken from here:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}
Community
  • 1
  • 1