C#Excel Interop错误:该文件正在被另一个进程使用

在我的项目中,mt的目标是编辑和移动文件。 我已经删除了所有的编辑部分,因为他们似乎没有造成错误。 我用这个代码testing了这个错误,它仍然会出现。

这是我的代码:

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); 

当运行这个时,我得到一个错误消息,当应用程序试图移动该文件: The process cannot access the file because it is being used by another process.

我很确定我已经closures了所有的COM对象,并且已经完成了我可以在网上find的所有build议,以使其工作。 任何想法,我已经错过了什么?

使用sysinterals来检查哪个进程导致此问题。 一般来说,我会在做这些事情之前certificate,如果你有写入权限的文件。

certificate写入访问的方法:

 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; } } 

看看: 找出哪个进程locking在Windows中的文件或文件夹 。