Articles in this section

How to Delete Bracketed Content from Previous Paragraphs Up to a Specific Word in .NET Core Word Document?

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can delete bracketed content from previous paragraphs up to a specific word in a Word document using C#.

Steps to delete bracketed content from previous paragraphs up to a specific word in a Word document:

  1. Create a new .NET Core console application project.

    Create console application in Visual Studio

  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.

    Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without trail message.

  1. Include the following namespaces in the Program.cs file
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following code example to delete bracketed content from previous paragraphs up to a specific word in a Word document.
    C#
// Load the existing word document
using(WordDocument document = new WordDocument(@"Data\Input.docx"))
{
   // Find the phrase using Find API (Specific Word, case-insensitive, whole-word match)
   TextSelection selection = document.Find("Importadores", true, true);
   // Proceed only if the phrase is found
   if (selection != null)
   {
       // Get the paragraph that contains the selected word
       WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph;
       // Get a owner section
       WSection ownerSection = (WSection)paragraph.OwnerTextBody.Owner;
       // Find the position (index) of the paragraph in the section
       int phraseParaIndex = ownerSection.Body.ChildEntities.IndexOf(paragraph);
       // Find the position of the word inside the paragraph
       int matchWordIndex = paragraph.ChildEntities.IndexOf(selection.GetAsOneRange());
       // Set how many paragraphs before the word we want to check
       int maxPreviousParagraphs = 6;
       // Call a method to remove content inside brackets before the word
       RemoveBlock(document, paragraph, phraseParaIndex, matchWordIndex, ownerSection, maxPreviousParagraphs);
       // Save the updated document to a file
       document.Save(@"../../../Output/Output.docx");
   }
}
  1. Use the following code example to delete content enclosed in brackets.
    C#
private static void RemoveBlock(WordDocument document, WParagraph paragraph, int phraseParaIndex, int matchWordIndex, WSection ownerSection, int maxPreviousParagraphs)
{
   // Initialize state
   int bracketCount = 0;
   bool isBracketFound = false;
   // Create a unique name for the temporary bookmark
   string bookmarkName = "Remove" + Guid.NewGuid().ToString();
   // Store the paragraph where the opening bracket '[' is found
   WParagraph openingBracketParagraph = null;
   // Store the character position of the opening bracket '['
   int openingBracketCharIndex = 0;
   // Loop backwards through previous paragraphs
   for (int i = phraseParaIndex; i >= 0 && i > phraseParaIndex - maxPreviousParagraphs; i--)
   {
       WParagraph currentParagraph = ownerSection.Paragraphs[i];
       // If it's the phrase paragraph, start from the word's position; otherwise, start from the end
       int start = i == phraseParaIndex ? matchWordIndex : currentParagraph.ChildEntities.Count - 1;
       // Loop through entities in reverse
       for (int j = start; j >= 0; j--)
       {
           // Check if the entity is a text range
           if (currentParagraph.ChildEntities[j] is WTextRange textRange)
           {
               string text = textRange.Text;
               // Loop through characters in reverse
               for (int k = text.Length - 1; k >= 0; k--)
               {
                   char ch = text[k];
                   // If we find a closing bracket
                   if (ch == ']')
                   {
                       isBracketFound = true;
                       bracketCount++;
                   }
                   // If we find an opening bracket
                   else if (ch == '[')
                   {
                       // If there's no matching closing bracket, stop processing
                       if (bracketCount == 0)
                           return;

                       // Reduce bracket count
                       bracketCount--;
                       // Save the position of the opening bracket
                       openingBracketCharIndex = k;
                       // Store the paragraph that contains this opening bracket,
                       openingBracketParagraph  = currentParagraph;
                   }
               }
           }
       }
   }
   // When a bracket is found and bracket count is 0, it means a complete and valid bracket pair is detected.
   if (isBracketFound && bracketCount == 0)
   {
       // Create and insert a bookmark start at the opening bracket position
       BookmarkStart bookmarkStart = new BookmarkStart(document, bookmarkName);
       openingBracketParagraph .ChildEntities.Insert(openingBracketCharIndex, bookmarkStart);
       // Create and insert a bookmark end after the specific word
       BookmarkEnd bookmarkEnd = new BookmarkEnd(document, bookmarkName);
       paragraph.ChildEntities.Insert(matchWordIndex + 1, bookmarkEnd);
       // Use Bookmarknavigator to delete content between the bookmarks
       BookmarksNavigator navigator = new BookmarksNavigator(document);
       navigator.MoveToBookmark(bookmarkName);
       navigator.DeleteBookmarkContent(true);
       // Remove the temporary bookmark from the document
       document.Bookmarks.Remove(navigator.CurrentBookmark);
   }
}

You can download a complete working sample to delete bracketed content from previous paragraphs up to a specific word in a Word document from the GitHub.

Output Word Document

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning about how to delete bracketed content from previous paragraphs up to a specific word in .NET Core Word document.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied