0

The problem I'm encountering is regarding the validation of a .docx document, to validate I'm using the next method:

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

But when it launches the exception (because the file is corrupted and cannot open it) leaves the file open and cannot be closed in the catch because it's out of context the WordprocessingDocument "instance?".

Then, when I have to delete the file I had to validate I can't because it's open by another process: Error Deleting

Thank you.

Miguel Cordero
  • 141
  • 1
  • 9
  • What library does `WordprocessingDocument` come from? – Markus Deibel Mar 05 '19 at 11:36
  • WordprocessingDocument Class Definition Namespace: DocumentFormat.OpenXml.Packaging Assembly: DocumentFormat.OpenXml.dll – Miguel Cordero Mar 05 '19 at 11:56
  • The exception occurs on the .Open (since it's (sometimes) a corrupted file and cannot open it) – Miguel Cordero Mar 05 '19 at 11:57
  • I would suggest loading the file into a `MemoryStream`, and passing that into `WordprocessingDocument`. This will ensure no file locks are held. – mjwills Mar 05 '19 at 12:03
  • while researching I though about that, but I wasn't sure how to do it since I have just started learning .net, but thanks, I'll try it and learn abuot MemoryStream – Miguel Cordero Mar 05 '19 at 12:07
  • Possible duplicate of [Save and load MemoryStream to/from a file](https://stackoverflow.com/questions/8624071/save-and-load-memorystream-to-from-a-file) – mjwills Mar 05 '19 at 12:19

1 Answers1

1

Maybe changing it to something like this helps:

  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();
}
Ehsan Kiani
  • 3,050
  • 1
  • 17
  • 19