Checking if an Excel Workbook is open

后端 未结 7 1228
孤街浪徒
孤街浪徒 2020-12-30 05:22

Is there a way to see if an Excel Workbook, say DataSheet.xls, is open (in use) or not? I would like to close that Workbook if it is opened.

7条回答
  •  無奈伤痛
    2020-12-30 06:05

    This is not especially nice - we'll try and open the file and examine the exception if it fails. I'm not sure you have any other choices in C#.

    However, it is important to only handle the correct exception: Basically we try open the file with no sharing allowed. If it fails, AND we get the correct type of exception AND we get the correct message in the exception, then we know it is open.

    // open the file with no sharing semantics (FileShare.None)
    using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
    {
        try
        {
            stream.ReadByte();
            return false;
        }
        catch (IOException ex)
        {
            // catch ONLY the exception we are interested in, and check the message too
            if (ex.Message != null 
                && ex.Message.Contains("The process cannot access the file"));
            {
                return true;
            }
    
            // if the message was incorrect, this was not the IOException we were looking for. Rethrow it.
            throw;
        }
    }
    

    Obviosuly this sort of approach is brittle with respect to the exception message being changed in a future release of .Net. You may wish to complement such functionality with a test that purposely locks a file and then calls this to check it correctly detects the message.

提交回复
热议问题