C#WINWORD.exe将不会退出 - 排序目录文件

时间:2016-11-18 20:04:57

标签: c# cmd com

我对C#不是那么擅长,但我努力做到最好, 这是一个小的控制台应用程序,应该得到2 arg2(通过传递args到exe或通过控制台输入)我有2个问题,我找不到任何其他解决方案

  1. 如果文件名有,则合并文件的顺序不正确 包括信件。恩。 (1.docx,2.docx,3.docx)它工作=> result.docx(1,2,3) (1test.docx,2rice.docx,3john.docx)=> result.docx(3,1,2)
  2. 在应用程序结束后无法关闭WINWORD.exe 完成
  3.   

    PS:这个exe由PHP行CMD.EXE

    调用

    我尝试了所有可能的命令来释放com对象然后关闭应用程序, 我的错在哪里?如何正确优化代码?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Office.Interop.Word;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.IO;
    
    namespace DocEngine
    {
        public class Parameter
        {
            public string Name;
            public string Value;
    
    
            // Note we need to give a default constructor when override it
            public Parameter()
            {
    
            }
    
        }
    
        class Program
        {
            public static void MergeDocuments(string fileName, List<string> documentFiles)
            {
    
                _Application oWord = new Microsoft.Office.Interop.Word.Application();
                _Document oDoc = oWord.Documents.Add();
                Selection oSelection = oWord.Selection;            
    
                foreach (string documentFile in documentFiles)
                {
                    _Document oCurrentDocument = oWord.Documents.Add(documentFile);
                    CopyPageSetup(oCurrentDocument.PageSetup, oDoc.Sections.Last.PageSetup);
                    oCurrentDocument.Range().Copy();
                    oSelection.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting);
                    if (!Object.ReferenceEquals(documentFile, documentFiles.Last()))
                        oSelection.InsertBreak(WdBreakType.wdSectionBreakNextPage);
                }
    
                oDoc.SaveAs(fileName, WdSaveFormat.wdFormatDocumentDefault);
                oDoc.Close();                      
    
                //TODO: release objects, close word application
                //Marshal.ReleaseComObject(oSelection);
                //Marshal.ReleaseComObject(oDoc);
                //Marshal.ReleaseComObject(oWord);
                Marshal.FinalReleaseComObject(oSelection);
                Marshal.FinalReleaseComObject(oDoc);
                Marshal.FinalReleaseComObject(oWord);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWord);
    
    
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oSelection);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                    oSelection = null;
                    oDoc = null;
                    oWord = null;
    
                    // A good idea depending on who you talk to...
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
    
    
            }
    
    
            public static void CopyPageSetup(PageSetup source, PageSetup target)
            {
                target.PaperSize = source.PaperSize;
    
                //target.Orientation = source.Orientation; //not working in word 2003, so here is another way
                if (!source.Orientation.Equals(target.Orientation))
                    target.TogglePortrait();
    
                target.TopMargin = source.TopMargin;
                target.BottomMargin = source.BottomMargin;
                target.RightMargin = source.RightMargin;
                target.LeftMargin = source.LeftMargin;
                target.FooterDistance = source.FooterDistance;
                target.HeaderDistance = source.HeaderDistance;
                target.LayoutMode = source.LayoutMode;
            }
    
    
            static void Main(string[] args)
            {
                if (args == null || args.Length == 0)
                  {
                    Console.WriteLine("Enter Path:");
                    Parameter parameter1 = new Parameter
                    {
                        Name = "dir",
                        Value = Console.ReadLine()
                    };
    
                    Console.WriteLine("FileName without ext:");
                    Parameter parameter2 = new Parameter
                    {
                        Name = "fileName",
                        Value = Console.ReadLine()
                    };
                    Console.WriteLine("Thank you! ");
    
                    Console.WriteLine("Test parameter1: [{0}] = [{1}]", parameter1.Name, parameter1.Value);
                    Console.WriteLine("Test parameter2: [{0}] = [{1}]", parameter2.Name, parameter2.Value);
    
                    try
                    {
    
                        List<string> result = Directory.EnumerateFiles(parameter1.Value, "*.doc", SearchOption.AllDirectories).Union(Directory.EnumerateFiles(parameter1.Value, "*.docx", SearchOption.AllDirectories)).ToList();
                        var filename = Path.Combine(parameter1.Value, parameter2.Value);
    
                        MergeDocuments(filename, result);
                    }
                    catch (UnauthorizedAccessException UAEx)
                    {
                        Console.WriteLine(UAEx.Message);
                    }
                    catch (PathTooLongException PathEx)
                    {
                        Console.WriteLine(PathEx.Message);
                    }
                }
    
               else
                {
    
                    //args = new string[2];
    
                    string sourceDirectory = args[0];
                    string filename1 = args[1];
    
                    try
                    {
                        List<string> result = Directory.EnumerateFiles(sourceDirectory, "*.doc", SearchOption.AllDirectories).Union(Directory.EnumerateFiles(sourceDirectory, "*.docx", SearchOption.AllDirectories)).ToList();
                        var filename = Path.Combine(sourceDirectory, filename1);
    
                        MergeDocuments(filename, result);
                    }
                    catch (UnauthorizedAccessException UAEx)
                    {
                        Console.WriteLine(UAEx.Message);
                    }
                    catch (PathTooLongException PathEx)
                    {
                        Console.WriteLine(PathEx.Message);
                    }
    
    
                }
            }
        }
    
    }
    

1 个答案:

答案 0 :(得分:2)

您不需要进行任何COM调用或显式GC调用,也不需要将事物显式设置为null。您只需致电Application.Quit