C# 如何检查工作簿是否打开

C# 如何检查工作簿是否打开,c#,exception,C#,Exception,我有一个用于清理Excel工作簿的小实用程序。当我试图打开一个已经在Excel中打开的文件进行清理时,它会抛出 “System.IO.IOException” 是否有某种方法可以在代码中进行检查,以便检查工作簿是否打开,如果打开,则抛出一个错误框,以便用户可以关闭工作簿并在继续之前关闭Excel public bool CleanFile(string docPath) { // Open the document for editing. using (SpreadsheetD

我有一个用于清理Excel工作簿的小实用程序。当我试图打开一个已经在Excel中打开的文件进行清理时,它会抛出

“System.IO.IOException”

是否有某种方法可以在代码中进行检查,以便检查工作簿是否打开,如果打开,则抛出一个错误框,以便用户可以关闭工作簿并在继续之前关闭Excel

public bool CleanFile(string docPath)
{
    // Open the document for editing.
    using (SpreadsheetDocument document = SpreadsheetDocument.Open(docPath, true))

您可以在打开文档之前使用此方法,如果返回true,请提醒用户

    public static bool IsFileOpen(string path)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        }
        catch (IOException ex)
        {
            if (ex.Message.Contains("being used by another process"))
                return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        return false;
    }

捕获异常是唯一合理的操作过程。您可能会检查它是否打开,确定它没有打开,然后在下一个代码块运行之前,用户碰巧打开了它-您的异常又回来了。当我尝试运行它时,收到以下消息:找不到类型或命名空间名称“FileStream”(您是否缺少using指令或程序集引用?)我认为您需要添加对System.IONote的引用,在该函数返回时,该文件可能已被另一个进程锁定-您也可以尝试在不检查的情况下访问该文件,因为无论如何,您都需要另一个异常处理程序来处理该块…尝试根据已本地化的错误消息文本执行任何操作都不是一个好主意。谢谢各位-我有“System.IO.Log”,但没有“System.IO”可用?