Ooxml SDK の代わりにプレーンな C# と XLinq を使用して、パッケージ (Word または Excel ドキュメント) のカスタム プロパティの値を変更しようとしています。ただし、ファイルが破損し、パッケージの変更が反映されません。
誰かがここで間違っていることを提案できますか?
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();
}