MS Word - Insert Text in worddocument after specified text

Viewed 78

found several matches to my request, but not for word, so I open a new thread. I got a word document. After a specified text, I want to insert some lines.

My code looks like that:

    public static class Program
{
    static void Main(string[] args)
    {
        string Filename = @"D:\...\MasterDoc.docx";
        string SearchFor = "Search this text and insert after it";
        string DocText = string.Empty;
        int InsertIndex = 0;

        //Run or attach MS Word
        Microsoft.Office.Interop.Word.Application wrdApp = RunOrAttachWordApplication();

        //Open masterfile
        Microsoft.Office.Interop.Word.Document doc = wrdApp.Documents.Open(Filename);

        //Get complete range
        Microsoft.Office.Interop.Word.Range rng = doc.Range();

        //Get document text
        DocText = rng.Text;

        //Search indes to insert text
        InsertIndex = DocText.IndexOf(SearchFor) + SearchFor.Length;

        //Define range at location for text pasting
        rng = doc.Range(InsertIndex, InsertIndex + 1);

        //Write 'Test...' on specified location
        rng.InsertAfter("Test...");

        //Close document
        doc.Close(); /*Right here I got a breakpoint and watch the result, so I do not need to save the document here*/

        //Close application
        wrdApp.Application.Quit();
        wrdApp.Quit();
        wrdApp = null;

        System.GC.Collect();

        System.Console.WriteLine("Ende...");
        System.Console.ReadKey();

    }

    public static Microsoft.Office.Interop.Word.Application RunOrAttachWordApplication()
    {
        if(System.Diagnostics.Process.GetProcessesByName("Word").Length > 0)
        {
            return System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.Application;
        }
        else
        {
            return new Microsoft.Office.Interop.Word.Application();
        }
    }
}

Well, it works - but not correctly. The text is inserted about 50 digits before the location, I want.

Does anybody know, how to fix that or I could imagine, that there is a much better methode to do that. I cannot modify the Masterdocument as it is recreated everytime by another, external program.

Thank you very much and regards, Jan

3 Answers

I find the Find.Execute method much cleaner and shorter for adding/replacing text in the Word VSTO.

doc.Range().Find.Execute(FindText: SearchFor, Replace: WdReplace.wdReplaceOne, ReplaceWith: SearchFor + " Test...");

It has many options, but for replacing the text I used:

 FindText - the text to find.
 Replace - how many replacements to make. [WdReplace][2] 
 ReplaceWith - the text.

I suspect that there is some metadata at the beginning of the file which is being ignored when you lookup the required index here:

DocText.IndexOf(SearchFor) + SearchFor.Length;

You can add the discrepancy to the insert, given that the amount is constant for all files:

//Search indes to insert text
InsertIndex = DocText.IndexOf(SearchFor) + SearchFor.Length + 50;

However, the most eloquent solution would be to stop using rng.InsertAfter and instead set rng.Text like this:

//Get document text
DocText = rng.Text;

//Search indes to insert text
InsertIndex = DocText.IndexOf(SearchFor) + SearchFor.Length;

//Update the text
DocText = DocText.Substring(0, InsertIndex) + "Test..." + DocText.Substring(InsertIndex);

// Set the new text
rng.Text = DocText;

Will unfortunatelly, the solution of EyIM does not work, as the textlength increased and its limited to 255 characters. Any other solutions? I really want to insert text, as there is some format in the document and I need to keep that.

Related