有没有办法以编程方式检查是否打开了Excel文件

时间:2012-07-11 07:03:37

标签: c# excel office-interop

我想检查一个特定的Excel文件是否已经打开。否则,当我在C#程序中重新打开相同的文件时,它将以只读格式打开。有没有办法找出文件是否已经打开?

1 个答案:

答案 0 :(得分:1)

如果该文件被其他程序打开,此代码可以帮助您解决问题,但是您将无法打开它

<!-- language: c# -->
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;
}

(你不能用它做任何事情,必须从程序关闭文件,打开它)