Search code examples
c#winformsms-wordoffice-interop

Word interop Document takes time to close, not able to delete temporary files


I'm building a C# WinForm application to edit a word document template (amongst other features). Since I have to insert a couple of images, I create a copy of them in the temp folder of the computer(from a database request) and want to delete all of those files when closing the app.

It seems like closing the actual document and ApplicationClass of Office.Interop.Word takes some time, and I would like to know if there's a way to trigger an event or anything similar when the application is actually closed.

Here's my function :

private void CloseDocument()
{
    if (_doc != null)
    {
        _doc.Close();
        _doc = null;
    }

    if (_appClass != null)
    {
        _appClass.Quit();
        _appClass = null;
    }

    File.Delete(tempFileName);

    foreach (string path in _imagePaths)
    {
        File.Delete(path);
    }
}

This function is binded to the OnHandleDestroyed Event. Unfortunately, when the document contains a bunch of images, it seems like it takes some times for the _doc and _appClass objects to actually close, leading the program to throw a System.IO.IOException : The process cannot access the file 'C:\Users\***\AppData\Local\Temp\alr1snsc.png' because it is being used by another process.

Is there any way to actually trigger a function when the document or ApplicationClass is properly close ? Note that if I insert a sleep before trying to delete the files, everything works fine, this is why I came to the conclusion that it's really about properly closing the document.


Solution

  • There is no built in way to do what you are looking to do. Although it is a common need, Microsoft has yet to address it. Because of this there are a couple of hacks that are common to accomplish this.

    1) Check for the temp file in a loop. Once it is gone you can delete your files.

    string fileName = "~" + <YourDocumentFileName>
                    do
                    {
    
                    } while (File.Exists(fileName));
    

    2) Try to reference something in the document and when it fails you can delete the files.

    bool docClosed = false;
                    string fileName;
                    do
                    {
                        try
                        {
                            fileName = _doc.OriginalDocumentTitle;
                        }
                        catch(Exception ex)
                        {
                            docClosed = true;
                        }
                    } while (!docClosed);