该进程无法访问另一个进程使用的文件

The process cannot access the file used by another process

我有一个 windows 应用程序(在 C# 中),它将 DOC 文件发送到 pdf 打印机,创建 pdf 并读取字节。应用使用word自动化打印pdf使用以下代码

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

创建 pdf 后,我使用

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

即使我将背景设置为 false,在目录中创建文件也需要一秒钟左右的时间,因此 readallbytes 因找不到文件而失败。我添加了下面的代码等待一个时间段所以pdf文件出现

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

但有时我会收到 filename.pdf 不存在的异常,或者我收到进程无法访问该文件,因为它正被另一个进程使用。我不明白为什么文件不可访问,因为我没有做任何会锁定文件的事情,另一件事我不明白的是我有时可以读取字节,但那并不总是发生。我没有找到错误,这是否意味着文件不是在睡眠时间范围内创建的?

与其尝试使用 Thread.Sleep 执行此操作,我建议您使用 FileSystemWatcher 对象来监视文件夹中是否有新创建或新重命名的文件。这将允许您设置一个事件以在文件准备好时触发代码以进行后续处理。