首页 > 解决方案 > 无法关闭和删除我检查是否已损坏的打开文件 (.docx)

问题描述

我遇到的问题是关于 .docx 文档的验证,以验证我正在使用下一个方法:

 public static bool ValidateWordDocument(string filepath)
    {
        WordprocessingDocument wordprocessingDocument;
        try
        {
            wordprocessingDocument = WordprocessingDocument.Open(filepath, true);
            wordprocessingDocument.Close();
            return true;
        }
        catch (Exception e)
        {
            _logger.LogError($"El archivo {filepath} esta corrupto o se trata de un archivo ");
            return false;
        }
    }

但是当它启动异常时(因为文件已损坏并且无法打开它)使文件保持打开状态并且无法在 catch 中关闭,因为它脱离了 WordprocessingDocument“实例?”的上下文。

然后,当我必须删除必须验证的文件时,我不能,因为它已被另一个进程打开: 错误删除

谢谢你。

标签: c#asp.net.netvisual-studiodocx

解决方案


也许将其更改为这样会有所帮助:

  try
    {
        wordprocessingDocument = WordprocessingDocument.Open(filepath, true);
        return true;
    }
    catch (Exception e)
    {
        _logger.LogError($"El archivo {filepath} esta corrupto o se trata de un archivo ");
        return false;
    }
finally{
 wordprocessingDocument.Close();
}

推荐阅读