locked
File is locked for editing RRS feed

  • Question

  • User-1499457942 posted

    Hi

       Sometimes when i save the existing file it asks for Save option because sometines Excel file remains open . How to ensure that before saving excel file should be closed.

    Thanks

    Friday, June 15, 2018 6:46 AM

All replies

  • User753101303 posted

    Hi,

    Make sure to properly Dispose all objects you are using and you may have to call https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.finalreleasecomobject(v=vs.110).aspx on those objects. It can also happen that Excel "shows" a dialog and wait for someone to answer.

    Excel was never intended to be used as a server side programming library. It's likely best to use alternate libraries whenever you can.

    Friday, June 15, 2018 7:50 AM
  • User-1499457942 posted

    Hi

      I have below code . Is there any other alternate way to do same thing.

    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);

    private void releaseObject(object obj)
    {
    try
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
    }
    catch (Exception ex)
    {
    obj = null;
    MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
    GC.Collect();
    }
    }

    Thanks

    Friday, June 15, 2018 8:31 AM
  • User1086429607 posted

    I dont see the code you're using but you could attempt the below to see if it fits inline with your code

    Worksheets sheets = excelApp.Worksheets; // <-- The important part
    Worksheet sheet = sheets.Open(...);
    ...
    Marshal.ReleaseComObject(sheets);
    Marshal.ReleaseComObject(sheet);

    Reference: https://stackoverflow.com/questions/158706/how-do-i-properly-clean-up-excel-interop-objects

    Friday, June 15, 2018 8:38 AM
  • User753101303 posted

    Depends on the rest of your code. I would check the value returned by ReleaseComObject. If not 0 you likely have some other object in your code (a Range or whatever) that would need to be disposed first.

    If I really can't bring that to 0 as expected my last resort would be to use FinalReleaseComObject instead to force the usage count to 0.

    Friday, June 15, 2018 12:26 PM