0

我想检查一个特定的 Excel 文件是否已经打开。否则,当我在 C# 程序中重新打开同一个文件时,它会以只读格式打开。有什么方法可以确定文件是否已经打开?

4

1 回答 1

0

If the file if opened by another program this code can help you figure it out, but you won't be able to open it

<!-- 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;
}

(BUt you can't do anything with it, the file must be closed from the program, which opened it)

于 2012-07-11T08:02:36.510 回答