Is there a way to programmatically check if a Exce

2019-02-21 07:05发布

问题:

I want to check whether a particular Excel file is already opened. Otherwise when I reopen same file in my C# program it is opening in read only format. Is there any way to find out if the file is already open?

回答1:

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)