cgraham720
cgraham720

Reputation: 147

Error when saving word doc C#

I currently have a program that merges individual word. documents as selected by the user. The user has 5 input options which allows selection of files. The combine button then calls the MsMerge.cs and combines the files selected into one. Below is an example of the command

private void combineButton2_Click(object sender, EventArgs e)
   {
       List <string> docList = new List<string>();
       docList.Add(selectedFile1);
       docList.Add(selectedFile2);
       docList.Add(selectedFile3);
       docList.Add(selectedFile4);
       docList.Add(selectedFile5);

       if (outputFolder2 != @"")
       {
           loadingForm.Show(); // To show the loading form

       string fileDate = DateTime.Now.ToString("dd-MM-yy");
       string fileTime = DateTime.Now.ToString("HH.mm.ss");
       string outcomeFolder2 = outputFolder2;
       string outputFile2 = "Combined Files " 
                           + fileDate + " @ " + fileTime + ".docx";
       string outputFileName2 = Path.Combine(outcomeFolder2, outputFile2);

       MsWord.Merge(docList.ToArray(), outputFileName2, true);

       loadingForm.Hide(); // to hide the loading form

       // Message displaying how many files are combined.
       MessageBox.Show("A total of " + docList.Count + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }

the problem I am having is when this 'merge' sequence is finished, I am presented with a "want to save changes to your document" - as if the program isn't correctly saving / combining the files selected. Due to this i think there is a clash between 'List' code shown above and the MsWord.cs,

  public class MsWord
{

    private static string defaultWordDocumentTemplate = @"Normal.dot";

    public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
    {
        Merge(filesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);
    }

    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)
        {
            // need to add handler
        }
        finally
        {
            // Finally, Close our Word application
            wordApplication.Quit(ref missing, ref missing, ref missing);
        }
    }

}

I initially had the 'combineButton' rigged up to merge a string [] array as opposed to a list which partially worked as it allowed 5 documents to be combined, however it required all 5 user inputs to be selected. if the user chose 2/3/4 files, the program would crash. This then led me to change my design from String array to a List.

I've been trying to find what is causing the clash but so far have failed to do so. Any help would be greatly appreciated

** update 1

seem to be getting error Exception thrown: 'System.Runtime.InteropServices.COMException' when the program throws up the save-as popup.

** update 2

program will merge documents in 5 selections are made. If the maximum 5 files are selected, the merge process will work fine, however if 2/3/4 files are selected, leaving vacancies in the selection - the popup error will occur, leading me to think that the vacant browse paths are clashing with the saving process.

Upvotes: 0

Views: 97

Answers (2)

cgraham720
cgraham720

Reputation: 147

As mentioned above, it was discovered that if the 5 list items were inserted it worked however 2/3/4 didn't, suggesting that the lack of files was causing a clash. i then added if statements to add the 'docs' to the list if they were not null, meaning it would only merge what was selected as opposed to looking for the 5 supposed files:

  private void combineButton2_Click(object sender, EventArgs e)
    {
        var docList = new List<string>();

     // if statements to determine if the file is added
        if (selectedFile1 != null)
        {
            docList.Add(selectedFile1);
        };

        if (selectedFile2 != null)
        {
            docList.Add(selectedFile2);
        };

        if (selectedFile3 != null)
        {
            docList.Add(selectedFile3);
        };

        if (selectedFile4 != null)
        {
            docList.Add(selectedFile4);
        };

        if (selectedFile5 != null)
        {
            docList.Add(selectedFile5);
        };

        string[] docListString = docList.ToArray();

        if (outputFolder2 != @"")
        {
            loadingForm.Show(); // To show the form

        string fileDate = DateTime.Now.ToString("dd-MM-yy");
        string fileTime = DateTime.Now.ToString("HH.mm.ss");
        string outcomeFolder2 = outputFolder2;
        string outputFile2 = "Combined Files " + fileDate + " @ " + fileTime + ".docx";
        string outputFileName2 = Path.Combine(outcomeFolder2, outputFile2);

        MsWord.Merge(docListString, outputFileName2, true);

        loadingForm.Hide(); // to hide the form

        // Message displaying how many files are combined. 
        MessageBox.Show("The " + docListString.Length.ToString() + " individual Documents selected have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

the code is abit crude however the basics are all there, just need to clean it up and add additional statements to ensure that more than 1 file must be selected for merging etc.

thank you all for the advice throughout!

Upvotes: 0

cgraham720
cgraham720

Reputation: 147

Finally got the program to work with no popup errors / save-as errors, purely from trial-and-error

private void combineButton2_Click(object sender, EventArgs e)
    {
        var docList = new List<string>();
        docList.Add(selectedFile1);
        docList.Add(selectedFile2);
        docList.Add(selectedFile3);
        docList.Add(selectedFile4);
        docList.Add(selectedFile5);
        string[] docListString = new string[docList.Count];

        if (outputFolder2 != @"")
        {
            loadingForm.Show(); // To show the form

        string fileDate = DateTime.Now.ToString("dd-MM-yy");
        string fileTime = DateTime.Now.ToString("HH.mm.ss");
        string outcomeFolder2 = outputFolder2;
        string outputFile2 = "Combined Files " + fileDate + " @ " + fileTime + ".docx";
        string outputFileName2 = Path.Combine(outcomeFolder2, outputFile2);

        MsWord.Merge(docListString, outputFileName2, true);

essentially i changed the List docList to Var docList in the button code, i then changed the list back into a string manually as opposed to using the .ToArray.

i'm not sure why the previous code didn't work, however there must have been some clash with the list and MsWord.cs to cause the error. Thank you to @AlexBell and @KirillShlenskiy for their suggestions throughout.

Upvotes: 1

Related Questions