简体   繁体   中英

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

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM