简体   繁体   English

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

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

In my project, mt aim is to edit and move a file. 在我的项目中,mt的目标是编辑和移动文件。 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. 运行此时,我在应用程序尝试移动文件时收到错误消息: 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. 我很确定我已经关闭了所有的COM对象,并完成了我在网上找到的所有建议,以使其工作。 Any ideas as to what I have missed? 关于我错过的任何想法?

Use sysinterals to check, which process cause this issue. 使用sysinterals检查哪个进程导致此问题。 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 . 看一下: 找出在Windows中锁定文件或文件夹的进程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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