【问题标题】:Unable to close and delete open file (.docx) that I checked if was corrupted无法关闭和删除我检查是否已损坏的打开文件 (.docx)
【发布时间】:2019-03-05 11:11:19
【问题描述】:

我遇到的问题是关于 .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“实例?”的上下文。

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

谢谢。

【问题讨论】:

  • WordprocessingDocument 来自哪个库?
  • WordprocessingDocument 类定义命名空间:DocumentFormat.OpenXml.Packaging 程序集:DocumentFormat.OpenXml.dll
  • .Open 上发生异常(因为它(有时)是损坏的文件,无法打开)
  • 我建议将文件加载到MemoryStream,然后将其传递到WordprocessingDocument。这将确保没有文件锁被持有。
  • 虽然我在研究这个问题,但由于我刚开始学习.net,所以我不知道该怎么做,但是谢谢,我会尝试一下并学习 MemoryStream

标签: c# asp.net .net visual-studio docx


【解决方案1】:

也许把它改成这样会有所帮助:

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

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多