Remove part of text

Hi,

I writing small console application that would create word document from txt file. When txt file is inserted into word document i would like to remove some text.

Removed text should start with "Header 2 Link" and finish with 5th end of line.

Image_2873_1740092662199

How to write c# code for this?

Thanks


3 Replies 1 reply marked as answer

SR Sindhu Ramesh Syncfusion Team February 24, 2025 11:32 AM UTC

Hi Branislav,
Based on the details provided, we understand that your requirement is to remove the text "Header2 Link" along with the next five paragraphs. Kindly refer to the code snippet below:

using (FileStream inputStream = new FileStream(@"../../../Input.txt", FileMode.Open, FileAccess.ReadWrite))

{

    using (WordDocument document = new WordDocument(inputStream))

    {

        TextSelection selection = document.Find("Header2 link", false, false);

        if (selection != null)

        {

            // Get the text range and its owner paragraph

            WTextRange textRange = selection.GetAsOneRange();

            WParagraph ownerParagraph = textRange.OwnerParagraph;

            // Remove the found text from the paragraph

            ownerParagraph.ChildEntities.Remove(textRange);

            WSection section = (WSection)ownerParagraph.OwnerTextBody.Owner;

            if (section != null)

            {

                int index = section.Body.ChildEntities.IndexOf(ownerParagraph);

                //Remove 5 entities next to owner paragraph

              for (int i = 0; i < 5; i++)

              {

                   // Exit loop if there are no more elements to remove beyond the given index.

                   if (section.Body.ChildEntities.Count <= index + 1)

                       break;

                   section.Body.ChildEntities.RemoveAt(index + 1);

              }

            }

          }

        using (FileStream outputStream = new FileStream(@"../../../Result.docx", FileMode.Create, FileAccess.Write))

        {

            document.Save(outputStream, FormatType.Docx);

        }

    }

}


In the given code snippet, we use the Find() method to locate the text "Header2 link" in the document and remove it from its owner paragraph. After that, we retrieve the index of the owner paragraph and remove the next five paragraphs following it.

For more detailed information, kindly refer the below UG:
Find and replace in Word document | DocIO | Syncfusion

Regards,
Sindhu Ramesh.


Marked as answer

BV Branislav Vucetic February 24, 2025 07:02 PM UTC

Hi Sindhu,

That is exactly what I needed.

Thanks on shared code.



CA Chrispine Agunja Imbo Syncfusion Team February 25, 2025 05:46 AM UTC

Hi Branislav,

You are welcome. Please let us know if you have any further questions. We are always happy to help.

Regards,

Chris


Loader.
Up arrow icon