1

I am opening multiple excel files in my application. Some will be automatically open when the application starts whereas some are opening at the run time.

Now I want to get data from an excel file on a button click. But before opening it, I want to check that excel file is already open.

  1. If it is open, I want to read from it directly.
  2. if it is not open, I want to open it and read from it.

But in both the cases I don't want to close the file after reading.`

I am using this method to open excel file.

objExcel = new Excel.ApplicationClass();
objWorkbook = objExcel.Workbooks.Open(...);`

Please help I am new to C#.

Anoop
  • 53
  • 2
  • 3
  • 9
  • Possible duplicate: http://stackoverflow.com/questions/6686886/how-to-access-an-already-opened-excel-file-in-c – Recipe Aug 01 '13 at 08:19
  • VBA example: http://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open-using-vba – Sergey Kucher Aug 01 '13 at 08:20
  • Another VBA check: http://stackoverflow.com/questions/3156676/checking-if-an-excel-workbook-is-open – martin Aug 01 '13 at 09:40

2 Answers2

2

if i understand corectly, you actually want to find whether some files are already open by this winform application, right?

if so, i think it should be fairly simple - just cache the opened workbook to some dictionary or so:

    static Dictionary<string, Workbook> _openedWorkBooks = new Dictionary<string, Workbook>();    
    public static Workbook GetWorkbook(string filePath)  {    
        Workbook wkb = null;    
        if (!(_openedWorkBooks.TryGetValue(filePath, out wkb)))    
        {
            // Open the file and store it into the dictionary    
        }

        return wkb;  
    }

    // remember to remove it when it's closed  
    public static CloseWorkbook()  
    {    // need to remove the corresponding key from the dictionary  
    }

also, you could use single instance of excel application too, and then all the opened workbook could be rerieved from App.Workbooks, however, it throws some exception sometimes (not sure why, but i did encounter before).

            var app = new Microsoft.Office.Interop.Excel.Application();
            var bk1 = app.Workbooks.Open("c:\temp\myfile.xls");
            var allOpenBks = app.Workbooks;

Actually it's still worth to call IsFileLock method to check the file is already open by other apps, otherwise you could encounter some errors.

Rex
  • 2,130
  • 11
  • 12
  • This answer is limited because it does not deal with the situation where workbook is open by some other means, in which case calling Open() yields an exception. We still need the Workbook objects somehow. – Alan Baljeu Oct 13 '18 at 18:30
-1

You can checkk, if you have Read-Write access:

        /// <summary>
    /// Check wether a file is locked
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public static 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;
    }

The Code is from some one else on StackOverflow.

Do .xlsx? If so, you can use for reading and writing Excel-Files OpenXML.

BendEg
  • 20,098
  • 17
  • 57
  • 131
  • What do you mean? If he have read-write acces, the excel file isn't opened. Because excel alway lock the opened file. – BendEg Aug 01 '13 at 08:32
  • As others have said, Excel would lock the file if its opened to prevent illegal modifications – aceminer Aug 01 '13 at 08:44
  • This check should definitely be performed, if the Excel document is opened elsewhere, there will be messageboxes being posted by Excel that you can not control within your application. The Excel-C# interface only works in a controlled manner if the Excel file can be opened in Write mode (assuming you are going to write to it from C#). – denver Jun 29 '15 at 14:53