我在后台用 Word 文档做几件事,有时,如果应用程序失败,MS Word 的实例会在后台运行。 重新启动后,它会尝试打开同一个文件,并且会出现一系列与之相关的问题。
我想了解(在这里找不到合适的答案)如何检查我尝试打开的文件是否已经打开。
我的代码:
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Open(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
wordApp.Visible = false;
如何在执行 wordApp.Documents.Open
之前检查文件是否已打开?
谢谢!
最佳答案
您可以尝试打开文件,如果文件已经打开,将抛出 IOException
并表明文件已打开:
public bool fileIsOpen(string path)
{
System.IO.FileStream a = null;
try
{
a = System.IO.File.Open(path,
System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
return false;
}
catch (System.IO.IOException ex)
{
return true;
}
finally
{
if (a != null)
{
a.Close();
a.Dispose();
}
}
}
关于c# - 在 C# 中打开之前检查 Word 文档是否已经打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007956/