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

时间:2015-12-18 15:28:33

标签: c# excel

在我的项目中,mt的目标是编辑和移动文件。为简单起见,我删除了所有编辑部分,因为它们似乎没有导致错误。我只用这段代码测试了错误,但仍然会发生。

这是我的代码:

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.

我很确定我已经关闭了所有COM对象,并完成了我在网上找到的所有建议,以使其工作。关于我错过的任何想法?

1 个答案:

答案 0 :(得分:2)

使用sysinterals检查哪个进程导致此问题。一般来说,如果您对该文件具有写入权限,我会在做这些事情之前进行证明。

校对写访问的方法:

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

看看:Find out which process is locking a file or folder in Windows