Search code examples
c#-4.0ms-wordinteropoffice-interop

how to detect Empty paragraph in Word Document using Microsoft.Office.Interop.Word in C#4.0?


I want to detect Empty paragraphs in Word Document using Microsoft.Office.Interop.Word. Suppose, if my word document have some empty paragraphs,then

Assume paragraph 3 is an empty paragraph...

Microsoft.Office.Interop.Word.Paragraph para = wordDoc.Content.Paragraphs[3];
int cSent = para.Range.Sentences.Count;

for (int j = 1; j <= cSent; j++)
{
 Microsoft.Office.Interop.Word.Range sent = para.Range.Sentences[j];
 MessageBox.Show("Sent lines :" + sent.Text.ToString());
}

Then empty paragraphs has taken the last sentence of the last non-empty paragraph.So, I can't able to detect empty paragraphs in my Word Document.

Is there a way to get Empty paragraph list?

Please Guide me to Get out of this problem...


Solution

  • Well, first, you may need to iterate through all the headers and footers of all sections if you also want to look for empty paras in those headers/footers.

    Second, something like this should work

    for each p in Doc.Content.Paragraphs
        if (p.Range.End - p.Range.Start) > 1 then (The paragraph is not empty)
    Next
    

    You may need to play with that "1" number, because I can't recall where Word sets the start and end points, empty paragraphs may be 2 chars long from start to end, not just one.

    You can also do things like

    p.Range.Sentences.Count > 0
    

    or

    p.Range.Characters.Count > 0
    

    But those techniques are typically slower than checking the start and end positions.