Checking if an Excel Workbook is open

后端 未结 7 1070
孤街浪徒
孤街浪徒 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:18

    Try this:

    try
    {
       Stream s = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
    
       s.Close();
    
       return true;
    }
    catch (Exception)
    {
       return false;
    }
    

    This will tryand open the file exclusively. If the file is already open it will throw an exception, where you can then (try to) close it and carry on.

提交回复
热议问题