Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建文件时发生Microsoft.Office.Interop.Word内存泄漏_C#_.net_Memory Leaks_Ms Word_Office Interop - Fatal编程技术网

C# 创建文件时发生Microsoft.Office.Interop.Word内存泄漏

C# 创建文件时发生Microsoft.Office.Interop.Word内存泄漏,c#,.net,memory-leaks,ms-word,office-interop,C#,.net,Memory Leaks,Ms Word,Office Interop,我有这样的课: public class WordInteropFileCreator { public void CreateWordDocument(object fileName, object saveAs, string clientFullName, ClientAdressInfo clientAdressInfo) { //Set Missing Value parameter - used to represent //

我有这样的课:

    public class WordInteropFileCreator
{
    public void CreateWordDocument(object fileName, object saveAs, string clientFullName, ClientAdressInfo clientAdressInfo)
    {
        //Set Missing Value parameter - used to represent
        // a missing value when calling methods through
        // interop.
        object missing = System.Reflection.Missing.Value;

        //Setup the Word.Application class.
        Word.Application wordApp = new Word.ApplicationClass();

        //Setup our Word.Document class we'll use.
        Word.Document aDoc = null;

        // Check to see that file exists
        if (File.Exists((string)fileName))
        {
            DateTime today = DateTime.Now;

            object readOnly = false;
            object isVisible = false;

            //Set Word to be not visible.
            wordApp.Visible = false;

            //Open the word document
            aDoc = wordApp.Documents.Open(ref fileName, ref missing,
                ref readOnly, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref isVisible, ref missing, ref missing,
                ref missing, ref missing);

            // Activate the document
            aDoc.Activate();

            // Find Place Holders and Replace them with Values.
            this.FindAndReplace(wordApp, "<name>", clientFullName);
            this.FindAndReplace(wordApp, "<address>", clientAdressInfo.GetStreetWithNumber());
            this.FindAndReplace(wordApp, "<city>", clientAdressInfo.GetCityWithPostalCode());
            this.FindAndReplace(wordApp, "<country>",clientAdressInfo.CountryCode != null && clientAdressInfo.CountryCode.ToUpper() == "PL" ? "  " : clientAdressInfo.CountryName);
        }
        else
        {
            throw  new Exception("File dose not exist " + fileName);
        }
        //object outputFileName = fileName.Replace(".doc", ".pdf");
        object fileFormat = Word.WdSaveFormat.wdFormatPDF;

        //Save the document as the correct file name.
        aDoc.SaveAs(ref saveAs, ref fileFormat, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing);

        object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
        //Close the document - you have to do this.
        aDoc.Close(ref saveChanges, ref missing, ref missing);

    }

    /// <summary>
    /// This is simply a helper method to find/replace 
    /// text.
    /// </summary>
    /// <param name="WordApp">Word Application to use</param>
    /// <param name="findText">Text to find</param>
    /// <param name="replaceWithText">Replacement text</param>
    private void FindAndReplace(Word.Application WordApp,
                                object findText,
                                object replaceWithText)
    {
        object matchCase = true;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundsLike = false;
        object nmatchAllWordForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiacritics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        WordApp.Selection.Find.Execute(ref findText,
            ref matchCase, ref matchWholeWord,
            ref matchWildCards, ref matchSoundsLike,
            ref nmatchAllWordForms, ref forward,
            ref wrap, ref format, ref replaceWithText,
            ref replace, ref matchKashida,
            ref matchDiacritics, ref matchAlefHamza,
            ref matchControl);
    }
}
                string firstPart = Path.Combine(reportPathDir, "first.pdf");
                string letterPath = Path.Combine(reportPathDir, repType);
                var creator = new WordInteropFileCreator();
                creator.CreateWordDocument(letterPath, firstPart, logicResult.SpecifcationClients[0].FullName, logicResult.ClientAdressInfo);
                var fs = new FileStream(secondPart, FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
                fs.Dispose();
当我在许多控制台应用程序中使用这段代码时,就会出现内存泄漏。有什么建议吗?
var creator=new WordInteropFileCreator()没有dispose方法。

您没有关闭Word,因此它将在后台继续运行:在处理结束时调用此函数

wordApp.Quit(ref nullObj, ref nullObj, ref nullObj);

与现有答案类似,但完成了您的方法。应该在文档关闭后立即退出

Word应用程序的退出方法:

wordApp.Quit();
  • 提示:Quit方法不需要任何输入参数
您应该在完成以下代码后退出
Word应用程序

public void CreateWordDocument(object fileName, object saveAs, string clientFullName, ClientAdressInfo clientAdressInfo)

{
    //Set Missing Value parameter - used to represent
    // a missing value when calling methods through
    // interop.
    object missing = System.Reflection.Missing.Value;

    //Setup the Word.Application class.
    Word.Application wordApp = new Word.ApplicationClass();

    //Setup our Word.Document class we'll use.
    Word.Document aDoc = null;

    // Check to see that file exists
    if (File.Exists((string)fileName))
    {
        DateTime today = DateTime.Now;

        object readOnly = false;
        object isVisible = false;

        //Set Word to be not visible.
        wordApp.Visible = false;

        //Open the word document
        aDoc = wordApp.Documents.Open(ref fileName, ref missing,
            ref readOnly, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref isVisible, ref missing, ref missing,
            ref missing, ref missing);

        // Activate the document
        aDoc.Activate();

        // Find Place Holders and Replace them with Values.
        this.FindAndReplace(wordApp, "<name>", clientFullName);
        this.FindAndReplace(wordApp, "<address>", clientAdressInfo.GetStreetWithNumber());
        this.FindAndReplace(wordApp, "<city>", clientAdressInfo.GetCityWithPostalCode());
        this.FindAndReplace(wordApp, "<country>",clientAdressInfo.CountryCode != null && clientAdressInfo.CountryCode.ToUpper() == "PL" ? "  " : clientAdressInfo.CountryName);
    }
    else
    {
        throw  new Exception("File dose not exist " + fileName);
    }
    //object outputFileName = fileName.Replace(".doc", ".pdf");
    object fileFormat = Word.WdSaveFormat.wdFormatPDF;

    //Save the document as the correct file name.
    aDoc.SaveAs(ref saveAs, ref fileFormat, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing);

    object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    //Close the document - you have to do this.
    aDoc.Close(ref saveChanges, ref missing, ref missing);
    wordApp.Quit();
}
public void CreateWordDocument(对象文件名、对象另存为、字符串clientFullName、ClientAddressInfo ClientAddressInfo)
{
//设置缺少的值参数-用于表示
//通过调用方法时缺少值
//互操作。
缺少对象=System.Reflection.missing.Value;
//设置Word.Application类。
Word.Application wordApp=新的Word.ApplicationClass();
//设置我们将使用的Word.Document类。
Word.Document aDoc=null;
//检查文件是否存在
如果(File.Exists((字符串)文件名))
{
DateTime today=DateTime.Now;
对象只读=false;
对象isVisible=false;
//将单词设置为不可见。
可见=false;
//打开word文档
aDoc=wordApp.Documents.Open(ref文件名,ref缺失,
ref readOnly、ref missing、ref missing、ref missing、,
缺少参考,缺少参考,缺少参考,缺少参考,
参考缺失,参考可见,参考缺失,参考缺失,
参考缺失,参考缺失);
//激活文档
aDoc.Activate();
//找到占位符并用值替换它们。
this.FindAndReplace(wordApp,“,clientFullName);
this.FindAndReplace(wordApp,“,clientAddressInfo.GetStreetWithNumber());
this.FindAndReplace(wordApp,“,clientAddressInfo.GetCityWithPostalCode());
this.FindAndReplace(wordApp,“,ClientAddressInfo.CountryCode!=null&&ClientAddressInfo.CountryCode.ToUpper()=”PL“”:ClientAddressInfo.CountryName);
}
其他的
{
抛出新异常(“文件不存在”+文件名);
}
//对象outputFileName=fileName.Replace(“.doc”和“.pdf”);
对象文件格式=Word.WdSaveFormat.wdFormatPDF;
//将文档另存为正确的文件名。
aDoc.SaveAs(ref SaveAs,ref fileFormat,ref missing,ref missing,
缺少参考,缺少参考,缺少参考,缺少参考,
缺少参考,缺少参考,缺少参考,缺少参考,
参考缺失、参考缺失、参考缺失、参考缺失);
object saveChanges=Word.WdSaveOptions.wdDoNotSaveChanges;
//关闭文档-您必须这样做。
aDoc.关闭(参考保存更改、参考缺失、参考缺失);
wordApp.Quit();
}

您需要退出word—类似于
wordApp.quit(ref nullObj,ref nullObj,ref nullObj)-并且,.NET 4+不需要missingstuartd->在该事件中插入什么?使用“退出”有什么缺点吗?@stuartd post可能与answare相同,我接受。谢谢