Miguel Cordero
Miguel Cordero

Reputation: 141

Unable to close and delete open file (.docx) that I checked if was corrupted

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.

Upvotes: 0

Views: 418

Answers (1)

Ehsan K. harchegani
Ehsan K. harchegani

Reputation: 3128

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

Upvotes: 1

Related Questions