how to check if excle is already open RRS feed

  • Question

  • User-1386791102 posted

    Hi all,

    I am working on excel import using Microsoft.Office.Interop.Excel. I am trying to read one excel file and put data into the mysql, if error occurs while reading the file i am writting error message in same excle file. 

    for opening the file i am using following code

    xlWorkBook = xlApp.Workbooks.Open(strImportFileName, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

    my problem is that if file is already open , my program is getting crushed.

    so please tell me how to check if the file is already open or not.

    Thanks and regards
    Harshad jadhav

    Thursday, October 7, 2010 3:12 AM


  • User-342606376 posted

    protected virtual bool IsFileLocked(FileInfo file)
            FileStream stream = null;
                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;
                if (stream != null)
            //file is not locked
            return false;


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 7, 2010 2:35 PM