Home » excel » C# Excel Interop Error: The file is being used by another process

C# Excel Interop Error: The file is being used by another process

Posted by: admin April 23, 2020 Leave a comment

Questions:

In my project, mt aim is to edit and move a file. I have removed all the editing sections for simplicity, as they do not seem to be causing the error. I have tested the error with just this code and it still occurs.

This is my code:

Application xlApp = new Application();
Workbooks xlWorkbooks = xlApp.Workbooks;
Workbook xlWorkbook = xlWorkbooks.Open(Path.GetFullPath(fileNameWithPath));
Sheets xlWorksheets = xlWorkbook.Sheets;
Worksheet xlWorksheet = xlWorksheets.get_Item(1);
Range xlRange = xlWorksheet.UsedRange;

string fileNameWithExtension = GetFileNameWithExtension(fileNameWithPath);

xlWorkbook.Close(false);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlWorksheets);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlWorkbooks);
Marshal.FinalReleaseComObject(xlApp);
xlRange = null;
xlWorksheet = null;
xlWorksheets = null;
xlWorkbook = null;
xlWorkbooks = null;
xlApp = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);

File.Move(fileNameWithPath, myNewPath);

When running this I am getting an error message when the application tries to move the file: The process cannot access the file because it is being used by another process.

I am pretty sure I have closed off all of the COM objects and have done all the recommendations I could find online to get this to work. Any ideas as to what I have missed?

How to&Answers:

Use sysinterals to check, which process cause this issue. In general i would proof before doing those things, if you have write access for the file.

Method for proofing write access:

public static bool FileHasWriteAccess(string Path)
{
    try
    {
        System.IO.File.Open(Path, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite).Dispose();
        return true;
    }
    catch (System.IO.IOException)
    {
        return false;
    }
}

Take a look at: Find out which process is locking a file or folder in Windows.