如何在不关闭我刚刚阅读的工作簿的情况下发布XML文件

时间:2016-03-12 01:02:23

标签: c# excel office-interop

这是我正在尝试做的一个简化版本。我想在Excel应用程序中打开一个excel文件,然后更改其中一个工作表中的数据并重新保存该文件。当我尝试保存时,我收到错误"该进程无法访问该文件,因为它正被另一个进程使用"。

问题是Workbooks.Open后文件仍然打开。有什么方法可以让Excel进程发布文件吗?我可以通过在Excel对象上执行Marshal发布来释放它,但之后我丢失了数据。我可以将它存储在对象的外部并重新添加它,但我宁愿找到一种方法来简单地从Excel对象中解除文件,使文件关闭。有没有办法做到这一点?

Microsoft.Office.Interop.Excel.Workbook workBook2;
Microsoft.Office.Interop.Excel.Application _application;
public void ReadAndSave(string path)
{
    bool isLocked1 = IsFileStillInUse(path); // this returns false

    _workBook = _application.Workbooks.Open(path);

    bool isLocked2 = IsFileStillInUse(path);  // this returns true

    if (isLocked2)
    {
        // How can I get the file to release so I can resave it?
    }
}
public static bool IsFileStillInUse(string filePath)
{
    if (!File.Exists(filePath))
    {
        return false;
    }

    try
    {
        using (StreamReader reader = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
        {
            return false;
        }
    }
    catch (IOException)
    {
        return true;
    }
}

0 个答案:

没有答案