Novacode.DocX.AddCoreProperty C# (CSharp) Method

AddCoreProperty() public method

Add a core property to this document. If a core property already exists with the same name it will be replaced. Core property names are case insensitive.
public AddCoreProperty ( string propertyName, string propertyValue ) : void
propertyName string The property name.
propertyValue string The property value.
return void
        public void AddCoreProperty(string propertyName, string propertyValue)
        {
            string propertyNamespacePrefix = propertyName.Contains(":") ? propertyName.Split(':')[0] : "cp";
            string propertyLocalName = propertyName.Contains(":") ? propertyName.Split(':')[1] : propertyName;

            // If this document does not contain a coreFilePropertyPart create one.)
            if (!package.PartExists(new Uri("/docProps/core.xml", UriKind.Relative)))
                throw new Exception("Core properties part doesn't exist.");

            XDocument corePropDoc;
            PackagePart corePropPart = package.GetPart(new Uri("/docProps/core.xml", UriKind.Relative));
            using (TextReader tr = new StreamReader(corePropPart.GetStream(FileMode.Open, FileAccess.Read)))
            {
                corePropDoc = XDocument.Load(tr);
            }

            XElement corePropElement =
              (from propElement in corePropDoc.Root.Elements()
               where (propElement.Name.LocalName.Equals(propertyLocalName))
               select propElement).SingleOrDefault();
            if (corePropElement != null)
            {
                corePropElement.SetValue(propertyValue);
            }
            else
            {
                var propertyNamespace = corePropDoc.Root.GetNamespaceOfPrefix(propertyNamespacePrefix);
                corePropDoc.Root.Add(new XElement(XName.Get(propertyLocalName, propertyNamespace.NamespaceName), propertyValue));
            }

            using (TextWriter tw = new StreamWriter(new PackagePartStream(corePropPart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                corePropDoc.Save(tw);
            }
            UpdateCorePropertyValue(this, propertyLocalName, propertyValue);
        }