BoldDesk®Customer service software offering ticketing, live chat, and omnichannel support, starting at $49/mo. for 10 agents. Try it for free.
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.
How to write c# code for this?
Thanks
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.
Hi Sindhu,
That is exactly what I needed.
Thanks on shared code.
Hi Branislav,
You are welcome. Please let us know if you have any further questions. We are always happy to help.
Regards,
Chris