(C#) win10 Memory Leakage in Microsoft.Office.Interop.Word

Asked 2 years ago, Updated 2 years ago, 48 views

I used the following source to extract the text from the word (.doc) in vs 1015, win7, but when I set it to win10, a memory leak started to occur.Please let me know how to deal with it.

Microsoft.Office.Interop.Word.Application word=null;
Microsoft.Office.Interop.Word.Document docs=null;
try
{
    word=new Microsoft.Office.Interop.Word.Application();
    object miss = System.Reflection.Missing.Value;
    object path=@"c:\1\1.doc";
    object readOnly = true;
    docs=word.Documents.Open(
        ref path,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss,
        ref miss);

       // text extraction processing

}
catch
{
}
finally
{
    object oMis=System.Reflection.Missing.Value;
    object oTru=true;
    object oFal = false;
    if(docs!=null)
    {
        docs.Close (refoFal, refoMis, refoMis);
        Marshall.ReleaseComObject(docs);
        docs = null;
    }

    object saveOption=Microsoft.Office.Interop.WdSaveOptions.wdDoNotSaveChanges;
    object originalFormat = Microsoft.Office.Interop.WdOriginalFormat.wdOriginalDocumentFormat;
    object routeDocument=false;
            ((_Application)word).Quit(ref saveOption, ref originalFormat, ref routeDocument);

    if(word!=null)
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
        word = null;
    }
    GC.Collect();
}

c#

2022-09-30 21:18

1 Answers

The leak is not presented, so it's hard to guess.

(_Application)word).Quit(ref saveOption, ref originalFormat, ref routeDocument);

Among the .NETs, the type cast corresponds to QueryInterface() in COM, which can also create a new copy of the word object and invoke Quit() for the created copy.You should avoid unwanted casts.

The code listed is written in Visual Studio 2008 or earlier, so if you organize it in Visual Studio 2010 or later format,

varword=new Application();
var docs=word.Documents.Open(@"c:\1\1.doc");

// text extraction processing

docs.Close(false);
word.Quit(WdSaveOptions.wdDoNotSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, false);

Is this the same problem?


2022-09-30 21:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.