6

I currently have a window-form that when a button is pressed, will merge 3 separate word docx's into one combined file.

 private void button1_Click(object sender, EventArgs e)
    {

            string document1 = @"C:\Test\Test1.docx";
            string document2 = @"C:\Test\Test2.docx";
            string document3 = @"C:\Test\Test3.docx";

            string[] documentsToMerge = { document1, document2, document3 };

            string outputFileName = String.Format(@"C:\Test\Merge\Combined.docx", Guid.NewGuid());

            MsWord.Merge(documentsToMerge, outputFileName, true);}

however, I want to select the containing folder ("C:\Test") as opposed to each individual file. This will allow me to combine alot more files without having to code them into the program individually, which would make it much more practical when using.

Is there any suggestions how to achieve this?

public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
    {
        object defaultTemplate = documentTemplate;
        object missing = System.Type.Missing;
        object pageBreak = Word.WdBreakType.wdSectionBreakNextPage;
        object outputFile = outputFilename;

        // Create a new Word application
        Word._Application wordApplication = new Word.Application();

        try
        {
            // Create a new file based on our template
            Word.Document wordDocument = wordApplication.Documents.Add(
                                          ref missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

            // Make a Word selection object.
            Word.Selection selection = wordApplication.Selection;

            //Count the number of documents to insert;
            int documentCount = filesToMerge.Length;

            //A counter that signals that we shoudn't insert a page break at the end of document.
            int breakStop = 0;

            // Loop thru each of the Word documents
            foreach (string file in filesToMerge)
            {
                breakStop++;
                // Insert the files to our template
                selection.InsertFile(
                                            file
                                        , ref missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

                //Do we want page breaks added after each documents?
                if (insertPageBreaks && breakStop != documentCount)
                {
                    selection.InsertBreak(ref pageBreak);
                }
            }

            // Save the document to it's output file.
            wordDocument.SaveAs(
                            ref outputFile
                        , 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
                        , ref missing);

            // Clean up!
            wordDocument = null;
        }
        catch (Exception ex)
        {
            //I didn't include a default error handler so i'm just throwing the error
            throw ex;
        }
        finally
        {
            // Finally, Close our Word application
            wordApplication.Quit(ref missing, ref missing, ref missing);
        }
    }
}

this is the MsWord.merge referenced in the first section of code. i've attempted using ' lnkResult.NavigateUrl = ' however i was unsuccessful.

Felix D.
  • 4,811
  • 8
  • 38
  • 72
cgraham720
  • 147
  • 1
  • 1
  • 11

2 Answers2

3

got the issue resolved using the getFiles method

string[] filePaths = Directory.GetFiles(@"c:\Test\");

string[] documentsToMerge = filePaths;

string outputFileName = (@"C:\Test\Merge\Combined.docx");

MsWord.Merge(documentsToMerge, outputFileName, true);

thank you for the help.

cgraham720
  • 147
  • 1
  • 1
  • 11
  • how about specifying a search pattern in `.GetFiles()` since he only wants word docs.... => https://msdn.microsoft.com/de-de/library/ms143316%28v=vs.110%29.aspx – Felix D. Mar 14 '16 at 08:48
  • 1
    @fede - good idea, i shall try this now. i assume you can filter for two types? to allow for doc and docx ? – cgraham720 Mar 14 '16 at 09:01
2

Since GetFiles() will get you all files the 2nd overload fits way better. To get all word docs (*.doc & *.docx) call:

//Add *.doc
string[] allWordDocuments = Directory.GetFiles("YourDirectory", "*.doc", SearchOptions.AllDirectorys); //Or if you want only SearchOptions.TopDirectoryOnly

As NineBerry told in his comment this will include also *.docx !!!

This will get you all *.doc & *.docx and ignore all other file types. This will avoide errors, since GetFiles("directoryName") will get all files which can lead to errors in MsWord.Merge() if you hand over files such as *.exe

So a simple approach would be:

string outputPath = @"C:\Test\Merge\Combined.docx";

MsWord.Merge(allWordDocuments, outputPath, true); 
Felix D.
  • 4,811
  • 8
  • 38
  • 72
  • 1
    You do not need to call GetFiles() twice. If you use GetFiles() with an extension with exactly three characters, files with a longer extension starting with these three characters are also found! So, the current version in the answer would return some files twice. – NineBerry Mar 14 '16 at 09:10
  • @nineberry - thank you for the advice, i simply added (@"c:\Test\", "*.doc"); to the end of my filepath - it now includes the .doc and docx – cgraham720 Mar 14 '16 at 09:21