How to remove empty lines from the word document in C#

With the help of Spire.Doc, we can easily add new paragraphs to the existing word document. Sometimes, there are many empty lines or blank paragraphs on the wording document when we copy the contents from the internet. We can use Spire.Doc to remove the empty lines at one time easily. This article will show you how to remove the empty lines from the word documents in C#.

Firstly, view the sample document with empty lines:

How to remove empty lines from the word document in C#

Step 1: Create a new word document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Traverse every section on the word document and remove the null and empty paragraphs.

foreach (Section section in doc.Sections)
{
    for (int i = 0; i < section.Body.ChildObjects.Count; i++)
    {
        if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
        {
            if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
            {
                section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
                i--;
            }
        }

    }
}

Step 3: Save the document to file.

string result = "result.docx";
doc.SaveToFile(result, FileFormat.Docx2013);

Effective screenshot after removing the empty lines from the word document:

How to remove empty lines from the word document in C#

Full codes:

{
    Document doc = new Document();
    doc.LoadFromFile("Sample.docx");
    
    foreach (Section section in doc.Sections)
    {
        for (int i = 0; i < section.Body.ChildObjects.Count; i++)
        {
            if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
            {
                if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
                {
                    section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
                    i--;
                }
            }

        }
    }
    
    string result = "result.docx";
    doc.SaveToFile(result, FileFormat.Docx2013);
  }