Click here to Skip to main content
15,891,849 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using (MemoryStream destination = new MemoryStream())
{
    using (FileStream sourcefilecopy = File.Open(file,
        FileMode.Open))
    { sourcefilecopy.CopyTo(destination); }

    using (WordprocessingDocument doc = WordprocessingDocument.Open(destination, true))
    {
        var docPart = doc.MainDocumentPart;

        if(docPart.HeaderParts.Count() > 0 ||
            docPart.FooterParts.Count() > 0)
        {
            docPart.DeleteParts(docPart.HeaderParts);
            docPart.DeleteParts(docPart.FooterParts);
            Document document = docPart.Document;
            var headers = document.Descendants<HeaderReference>().ToList();
            foreach (var header in headers)
            {
                header.Remove();
            }

            var footers = document.Descendants<FooterReference>().ToList();
            foreach (var footer in footers)
            {
                footer.Remove();
            }
            document.Save();
        }
    }
}

This code makes a copy of a document using a mememorystream, then check if the cound > 0 on header and footer and removes it,
But if my document dont have any footer and header it get the error The specifield package is invalid the main part is missing
Posted
Updated 11-Feb-15 20:26pm
v3
Comments
Kornfeld Eliyahu Peter 12-Feb-15 2:43am    
I do not rally understand your problem, but I can see a logical flow in your code...
You are asking if either header or footer exists and than clean both, you should ask - and clean - separately...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900