openxml sdk2.5 : http://download.microsoft.com/download/5/5/3/553C731E-9333-40FB-ADE3-E02DC9643B31/OpenXMLSDKV25.msi
openxml Tool v2.5: http://download.microsoft.com/download/5/5/3/553C731E-9333-40FB-ADE3-E02DC9643B31/OpenXMLSDKToolV25.msi
dome: RemoveComments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
namespace AcceptRevisions
{
public static class LocalExtensions
{
public static XDocument GetXDocument(this OpenXmlPart part)
{
XDocument xdoc = part.Annotation<XDocument>();
if (xdoc != null)
return xdoc;
using (StreamReader sr = new StreamReader(part.GetStream()))
using (XmlReader xr = XmlReader.Create(sr))
xdoc = XDocument.Load(xr);
part.AddAnnotation(xdoc);
return xdoc;
}
}
class Program
{
public static void RemoveComments(WordprocessingDocument document)
{
// remove w:commentRangeStart, w:commentRangeEnd, w:commentReference
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();
// pre-atomize the XName objects so that they are not atomized for every item in the collection
XName commentRangeStart = w + "commentRangeStart";
XName commentRangeEnd = w + "commentRangeEnd";
XName commentReference = w + "commentReference";
mainDocumentXDoc.Descendants()
.Where(x => x.Name == commentRangeStart || x.Name == commentRangeEnd || x.Name == commentReference)
.Remove();
// remove the comment part
document.MainDocumentPart.DeletePart(document.MainDocumentPart.WordprocessingCommentsPart);
using (XmlWriter xw =
XmlWriter.Create(document.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
mainDocumentXDoc.Save(xw);
}
public static bool HasComments(WordprocessingDocument document)
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();
return mainDocumentXDoc.Descendants(w + "commentReference").Any();
}
static void Main(string[] args)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open("Test.docx", true))
{
Console.WriteLine(HasComments(doc));
RemoveComments(doc);
Console.WriteLine(HasComments(doc));
}
}
}
}
save Document:
byte[] byteArray = File.ReadAllBytes("c:\data\hello.docx"); using (MemoryStream stream = new MemoryStream()) { stream.Write(byteArray, 0, (int)byteArray.Length); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true)) { // Do work here } // Save the file with the new name File.WriteAllBytes("C:\data\newFileName.docx", stream.ToArray()); }