Search code examples
c#arraysthread-sleepword-automation

The process cannot access the file used by another process


I have a windows application (in C#) which sends a DOC file to a pdf printer, creates pdf and read the bytes. The application uses word automation to print pdf using the following code

object Background = false; //to make sure the pdf file is created before continuing
wordApp.Visible = true;
wordApp.ActivePrinter = printerName;/*pdf printer*/
wordDoc = wordApp.Documents.Open(ref objFileName,
 ref missing, ref objFalse, ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing, ref missing, ref missing,
 ref missing, ref missing, ref missing, ref missing, ref missing);
wordDoc.Activate();

wordDoc.PrintOut( Background, ref missing, ref Range, ref missing,
    ref missing, ref missing, ref missing, ref Copies,
    ref missing, ref PageType, ref PrintToFile, ref Collate,
    ref missing, ref ManualDuplexPrint, ref PrintZoomColumn,
    ref PrintZoomRow, ref missing, ref missing);

do
{System.Threading.Thread.Sleep(10);
} while (wordApp.BackgroundPrintingStatus > 0);
wordDoc.Close(ref objFalse, ref missing, ref missing);

After creating the pdf, i read the bytes using

bytes = System.IO.File.ReadAllBytes(Path.ChangeExtension(fileName, "pdf"));

Even though i set the background to false, it take a second or so for the file to be created in the directory, so readallbytes fails as it cannot find the file. I added the following code to wait for a time period so the pdf file appears

while (!File.Exists(Path.ChangeExtension(fileName, "pdf")))
{
 System.Threading.Thread.Sleep(1000);
}
bytes = System.IO.File.ReadAllBytes(Path.ChangeExtension(fileName, "pdf"));

But sometimes i get exception that filename.pdf does not exist or i get process cannot access the file as it is being used by another process. I do not understand why file is not accessible as i am not doing anything that would lock the file and another thing i don't get it is i could read the bytes sometimes but thats does not happen always. I get not found error, does that mean the file is not created with in the sleep timeframe?


Solution

  • Instead of trying to do this with Thread.Sleep, I suggest you use a FileSystemWatcher object to monitor the folder for newly-created or newly-renamed files. This will allow you to set up an event to trigger the code for subsequent processing when the file is ready.