Unable to Remove Header if header contains more than one section

Hi,
Please use the attached word document. Header in 1st page was removed. But unable to remove the header in 2nd page since it is created under different section. I have tried with the below code:

foreach (Section section in doc)
{
    foreach(HeaderFooter hf in section.HeadersFooters)
    {
        hf.Remove();
    }
}

Also I treid with the below code:

NodeCollection headersFooters = doc.GetChildNodes(NodeType.HeaderFooter, true);
foreach(HeaderFooter node in headersFooters)
{
    if (node.HeaderFooterType == HeaderFooterType.HeaderEven ||
        node.HeaderFooterType == HeaderFooterType.HeaderFirst ||
        node.HeaderFooterType == HeaderFooterType.HeaderPrimary)
        node.Remove();
}

Hi Ponraj,

Thanks for your inquiry. You can remove all headers from all sections by using the following code snippet:

Document doc = new Document(@"C:\test\HeaderFooterIssue+.doc");
foreach (Section section in doc)
{
    HeaderFooter header;

    header = section.HeadersFooters[HeaderFooterType.HeaderFirst];
    if (header != null)
        header.Remove();
    // Primary header is the header used for odd pages.
    header = section.HeadersFooters[HeaderFooterType.HeaderPrimary];
    if (header != null)
        header.Remove();
    header = section.HeadersFooters[HeaderFooterType.HeaderEven];
    if (header != null)
        header.Remove();
}
doc.Save(@"C:\test\HeaderFooterIssue_out.doc");

I hope, this will help.

Best Regards,

Thanks. This code is working fine. Is it possible to optimize the code rather than checking for each item like primary or even etc.

Hi,

Thanks for your request. Please note that there can be a maximum of only one HeaderFooter of each HeaderFooterType per Section. Talking about headers, there are of three types i.e. HeaderFirst, HeaderPrimary and HeaderEven; so up to three different headers are possible in a section (for first, even and odd pages). Moreover, the code posted earlier is already optimized in your case.

If we can help you with anything else, please feel free to ask.

Best Regards,

Hi there,

Thanks for your inquiry.

Sure, please try using the code below to remove all headers and footers from the document without the need to go through each header footer separately.

foreach (Section section in doc)
    section.ClearHeadersFooters();

Thanks,