How to update custom properties of a package (Word, Excel) without using Ooxml SDK?
-
jeudi 9 août 2012 16:32
Hi,
I am trying to change the value of a custom property of a Package (Word or Excel documents) using plain C# and XLinq instead of Ooxml SDK. However, it corrupts the file and does not reflect the change in the package.
Can someone please suggest what is incorrect here?
Package package = null; try { package = Package.Open("NewCustomProp.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite); foreach (var packagePart in package.GetParts()) { if (packagePart.ContentType == "application/vnd.openxmlformats-officedocument.custom-properties+xml") { var packageStream = packagePart.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite); using (StreamReader streamReader = new StreamReader(packageStream)) { try { string ns = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"; XDocument xDocument = XDocument.Parse(streamReader.ReadToEnd()); var properties = xDocument.Descendants(XName.Get("property", ns)).Where(x => x.Attribute(XName.Get("name")).Value == "NewCustomProp").ToList(); if (properties.Count > 0) { foreach (var currentProperty in properties) { var valueNode = currentProperty.Descendants().First(); valueNode.Value = "This is new value of Custom Property"; } StringBuilder innerXmlSB = new StringBuilder(); xDocument.Nodes().ToList().ForEach(node => innerXmlSB.Append(node.ToString())); string innerXml = innerXmlSB.ToString(); byte[] buffer = Encoding.UTF8.GetBytes(innerXml); packageStream.Write(buffer, 0, buffer.Length); //tried this as well //xDocument.Save(packageStream); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } } } package.Flush(); } finally { package.Close(); }
Thanks in anticipation!
Punit Ganshani | www.ganshani.com
Toutes les réponses
-
vendredi 10 août 2012 09:53Modérateur
Hi,
Thanks for posting in the MSDN Forum.
I have reproduced your issue with the code but no luck. My word file is also corrupt and can not be opened. This is a quich note to tell you that I will do further research on the issue. Much appreciated for your patience and understanding. Moreover, I recommand you a thread I think would be helpful. Maybe you can find some useful suggestions with your question.http://support.microsoft.com/kb/195425
Have a good day.
Best Regards,
Leo_Gao [MSFT]
MSDN Community Support | Feedback to us
- Proposé comme réponse Leo_GaoModerator jeudi 16 août 2012 06:47
- Marqué comme réponse Leo_GaoModerator jeudi 16 août 2012 06:47

