none
Find and replace text in Ms word document using c# RRS feed

  • Question

  • Hi,

    We have requirement to find and replace the text in Ms word document For ex: <<First Name >> should be replaced with

    "John Peru "and save as word document. 

    Could you please let me know the best solution using c#. No third part dll.

    Regards,

    Patil



    Tuesday, December 10, 2019 3:51 PM

All replies

  • As suggested by Castorix31, I Word Interop. The replace code is below.

    I had trouble with getting the Replace to work throughout the whole document, so I ended up running the Replace on the StoryRange.

    Ethan

    private static void FindAndReplaceInCompleteWordDocument(Application word, Document template, string replaceWhat, string replaceWith)
            {
                template.Select();
                Replace(word, replaceWhat, replaceWith);
                foreach (Range storyRange in template.StoryRanges)
                {
                    storyRange.Select();
                    Replace(word, replaceWhat, replaceWith);
                }
            }
         
            private static void Replace(Application word, string replaceWhat, string replaceWith)
            {
                if (replaceWhat != null && !string.IsNullOrWhiteSpace(replaceWhat))
                {
                    object missing = Type.Missing;
                    Selection selection = word.Selection;
                    string replacementText = string.Empty;
                    if (replaceWith.Length < 240)
                    {
                        replacementText = replaceWith;
                    }
                    else
                    {
                        ThreadStart starter = new ThreadStart(() => Clipboard.SetText(replaceWith));
                        Thread clipboardThread = new Thread(starter);
                        clipboardThread.SetApartmentState(ApartmentState.STA);
                        clipboardThread.Start();
                        clipboardThread.Join();
                        //This replace works with strings longer than 255 characters
                        //                    Clipboard.SetText(replaceWith);
                        replacementText = "^c";//Replaces with clipboard contents
                    }
                    Find finder = selection.Find;
                    finder.Execute(replaceWhat,
                     missing,
                     missing,
                     missing,
                     missing,
                     missing,
                     missing,
                     missing,
                     missing,
                     replacementText,
                     WdReplace.wdReplaceAll,
                     missing,
                     missing,
                     missing,
                     missing);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(finder);
                }
            }



    Ethan Strauss

    Tuesday, December 10, 2019 6:41 PM
  • Hi ppatil12,

    Thank you for posting here.

    For your question, you want to replace text in word file.

    To achieve this, you can also use this NuGet package: Spire.Doc.

    Here is a code example.

            static void Main(string[] args)
            {
                Document document = new Document();
                document.LoadFromFile(@"D:\test\docs\test.docx");
                document.Replace("", "", false, true);
                document.SaveToFile(@"D:\test\docs\test.docx",FileFormat.Docx);
            }
    

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 11, 2019 3:26 AM
  • I think the asker made this clear: No 3rd party DLL.

    So Spire.Doc is not a solution.

    IMO, even using Word Interop is marginal.

    I would have recommanded to disect the XML himself, but even for "mail merge" fields (his example got me think it's the primary purpose the code would be used for) I remember there are like 30% of cases where even MS Word can save the marker into multiple runs, so this is no simple task. (In the end I wrote something about 600 LOC to handle all the cases)

    Wednesday, December 11, 2019 4:46 AM
    Answerer