2016-07-27 14 views
0

Ich versuche, eine Menge von PDFs aus mehreren Word-Dokumente zu erstellen. Leider kann ich nicht schließen/aufräumen (Garbage Collection). Daher ist der Speicherverbrauch sehr hoch, und schließlich wird das Programm heruntergeladen.Office-Anwendungen Wort in C#

Hier ist mein Code. Ich hoffe, dass ihr schlauen Jungs mich zu einer Lösung führen könnt.

//************************************************************** 
// Please notice: 
// 
// this.Files is an array with filepath and filenames e.g.: 
// {"x:\doc\doc1.doc", "x:\doc\doc2.doc",...,"x:\doc\docn.doc"}. 
// 
// Please notice: 
//************************************************************** 


public void wordToPDF() { 

    string LS_fileName = ""; 
    string LS_fileExtension = ""; 
    string LS_PDF = ".pdf"; 

    try 
    { 
     foreach (string Filename in this.Files) 
     { 
      LS_fileName = Path.GetFileName(Filename); 
      if (Path.GetExtension(Filename) == ".doc" || Path.GetExtension(Filename) == ".docx") 
      { 
       // Convert to PDF: 
       Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); 
       wordDocument = appWord.Documents.Open(GlobalVar.TempFiles + LS_fileName); 
       LS_fileExtension = Path.GetExtension(Filename); 

       LS_fileName = LS_fileName.Replace(LS_fileExtension, LS_PDF);     int i = 0; 
       foreach (string value in this.Files) 
       { 
        if (value == Filename) 
        { 
         this.Files[i] = this.Files[i].Replace(LS_fileExtension, LS_PDF); 
         break; 
        } 
        i++; 
       } 
       wordDocument.ExportAsFixedFormat(GlobalVar.TempFiles + LS_fileName, MSWORD.WdExportFormat.wdExportFormatPDF); 
       System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("getFiles Hello I must be going."); 
    } 
} 
} 

// UPDATE # 1:

public void wordToPDF() { 

    string LS_fileName = ""; 
    string LS_fileExtension = ""; 
    string LS_PDF = ".pdf"; 
    int i = 0; 

    MSWORD.Application appWord = new MSWORD.Application(); 

    try 
    { 
     foreach (string Filename in this.Files) 
      { 
       LS_fileName = Path.GetFileName(Filename); 
        if (Path.GetExtension(Filename) == ".doc" || Path.GetExtension(Filename) == ".docx") 
        { 
         // Convert to PDF: 
         wordDocument = appWord.Documents.Open(GlobalVar.TempFiles + LS_fileName); 
         LS_fileExtension = Path.GetExtension(Filename); 

         LS_fileName = LS_fileName.Replace(LS_fileExtension, LS_PDF); 
         i = 0; 
         foreach (string value in this.Files) 
         { 
          if (value == Filename) 
          { 
           this.Files[i] = this.Files[i].Replace(LS_fileExtension, LS_PDF); 
           break; 
          } 
          i++; 
          } 
          wordDocument.ExportAsFixedFormat(GlobalVar.TempFiles + LS_fileName, MSWORD.WdExportFormat.wdExportFormatPDF); 
        } 
    } 
} 
    catch (Exception ex) 
    { 
     Console.WriteLine("getFiles Hello I must be going."); 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord); 
    wordDocument.Close(); 
    if (appWord != null) 
    { 
     appWord.Quit(); 
     appWord = null; 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
    } 
} 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord); 
wordDocument.Close(); 
    if (appWord != null) 
    { 
     appWord.Quit(); 
     appWord = null; 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
    } 
} 

// UPDATE # 2:

public void wordToPDF() 
{ 

    string LS_fileName = ""; 
    string LS_fileExtension = ""; 
    string LS_PDF = ".pdf"; 
    object missingType = Type.Missing; 
    object SaveChanges = Type.Missing; 
    object OriginalFormat = Type.Missing; 
    object RouteDocument = Type.Missing; 

    MSWORD.Application appWord = new MSWORD.Application(); 

    try 
    { 
     foreach (string Filename in this.Files) 
      { 
       LS_fileName = Path.GetFileName(Filename); 
        if (Path.GetExtension(Filename) == ".doc" || Path.GetExtension(Filename) == ".docx") 
        { 
          // Convert to PDF: 
      wordDocument = appWord.Documents.Open(GlobalVar.TempFiles + LS_fileName); 
          LS_fileExtension = Path.GetExtension(Filename); 

          LS_fileName = LS_fileName.Replace(LS_fileExtension, LS_PDF); 
          int i = 0; 
          foreach (string value in this.Files) 
          { 
           if (value == Filename) 
           { 
            this.Files[i] = this.Files[i].Replace(LS_fileExtension, LS_PDF); 
            break; 
           } 
           i++; 
          } 
          wordDocument.ExportAsFixedFormat(GlobalVar.TempFiles + LS_fileName, MSWORD.WdExportFormat.wdExportFormatPDF); 

          wordDocument.Close(); 
        } 
       } 
    } 
      catch (Exception ex) 
      { 
       Console.WriteLine("getFiles Hello I must be going."); 
       System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord); 

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

      appWord.Quit(ref object SaveChanges = Type.Missing, ref object OriginalFormat); 
      if (appWord != null) 
      { 
       appWord = null; 
       GC.Collect(); 
       GC.WaitForPendingFinalizers(); 
       GC.Collect(); 
       GC.WaitForPendingFinalizers(); 
     } 
    } 
} 
+0

Verwendung ‚entsorgen‘ oder ‚Verwendung‘ Aussagen. – user3150546

+0

Dafür brauche ich Hilfe. Danke im Voraus. –

Antwort

0

Offenbar funktioniert das Beenden der WinWord-Anwendung nicht. Hense eine rudimentäre Lösung angewendet wird:

Process[] processes = Process.GetProcessesByName("winword"); 
foreach (var process in processes) 
{ 
    try 
    { 
     process.Kill(); 
    } 
    catch (Exception) 
    { 
    // handle the exception...      
    } 

} 
// That solved the problem. 
// Thanks for your help :-). 
1

Stellen Sie sicher, das Dokument und Anwendung zu schließen, bevor Sie das COM-Objekt-Freigabe, dann entsorgen und vielleicht erzwinge GC.Collect().
Edit: Wenn Sie Wort mehrmals verwenden, ist es ausreichend, Word einmal zu starten und öffnen Sie Ihre Dateien für den PDF-Export, dann schließen Sie nacheinander. Schließlich schließe wordApp.
Edit2: Sie sollte ich auf 0 zurückgesetzt, jedes Mal, wenn Sie Ihre innere Schleife

+0

Ich habe das ohne Glück versucht. Dafür brauche ich Hilfe. Danke im Voraus. –

+0

können Sie das Close WordDocument hinzufügen und schließlich AppWord zu Ihrem Code schließen? Vielleicht war es fehl am Platz ... – Sebastian

+0

wordDocument.Close(); funktioniert gut Dann appWord.Quit(); ergibt: "Ein COM-Objekt, das von seinem RCW getrennt wurde, kann nicht verwendet werden." Dies ist die Nachricht, die ich bekomme –

1
  1. Use „mit“ Klausel
  2. Extrahieren Sie die Schleife Inhalt in einem separaten Verfahren beginnen die Dinge für die GC
  3. GC sammeln zu vereinfachen sollte nur aufgerufen werden, wenn Sie die Wahl nicht haben

ich verstehe nicht, warum Sie für Schleife die innere tun

+0

1 Irgendwie kann ich nicht benutzen- es hat nicht funktioniert :-( 2 + 3. Ich werde das versuchen. Der Grund dafür ist, dass this.Files andere Dokumente (PDFs) enthält. So muss es nur PDFs basierend auf dem Wort Dokumente erstellen. Der Inhalt von this.Files (wenn Word-Dokument) wird dann mit der PDF-Erweiterung aktualisiert. Das Endergebnis ist dann, dass this.Files nur den Pfad, den Namen und die Erweiterung der PDF enthält. –

+0

Verwenden ist nur für IDisposable Objekte – Mitzi

2

1) Versuchen Sie, diese lin zu bewegen aus der Schleife. (foreach (string Filename in this.Files))

Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); 

2) Schließen Sie alle Documents am Ende der Schleife (foreach (string Filename in this.Files)), die alle Word-Fenster schließen, oder Sie können Sie für gespeicherte Dokument Verknüpfung speichern und schließen.

Edit:

foreach (string Filename in this.Files) 
     { 
      LS_fileName = Path.GetFileName(Filename); 
       if (Path.GetExtension(Filename) == ".doc" || Path.GetExtension(Filename) == ".docx") 
       { 
        // Convert to PDF: 
        wordDocument = appWord.Documents.Open(GlobalVar.TempFiles + LS_fileName); 
        LS_fileExtension = Path.GetExtension(Filename); 

        LS_fileName = LS_fileName.Replace(LS_fileExtension, LS_PDF); 
        i = 0; 
        foreach (string value in this.Files) 
        { 
         if (value == Filename) 
         { 
          this.Files[i] = this.Files[i].Replace(LS_fileExtension, LS_PDF); 
          break; 
         } 
         i++; 
         } 
         wordDocument.ExportAsFixedFormat(GlobalVar.TempFiles + LS_fileName, MSWORD.WdExportFormat.wdExportFormatPDF); 
         wordDocument.Close(missing, missing, missing); 
       } 
} 

Discription: Durch Wortmodell, Wort ist eine Anwendung, die einen Hauptteil Microsoft.Office.Interop.Word.Application es enthält alle Dokumente, die zur Laufzeit öffnen, suchen diese Dokumente wie eine Standalone-Anwendungen (Windows) aber sie sind nicht.

+0

Ich habe Ihren Kommentar und einige Artikel gelesen. Ich habe deinen Schritt 1 wie in "Bewährte Praxis" befolgt. Das funktioniert - allerdings. In Bezug auf Schritt 2: Es scheint, ich kann das Dokument nicht schließen. Kannst du mich bitte führen? Danke im Voraus. –

+0

Siehe Update Nr. 1. –

+1

[Word.Document.Close()] (https://msdn.microsoft.com/en-US/library/af6z0wa2.aspx) ** Schließen eines Dokuments, das Sie nach Name angeben ** Der Absatz wäre das einfachste Beispiel, wenn Sie einen Link für ein geöffnetes Dokument haben. – Shakra