Search code examples
c#openxmlopenxml-sdk

DocumentFormat.OpenXml Modify Creator Propery of Document


I wish to replace Word Document Creator metadata with something else but its not persisted when calling WordprocessingDocument.Save(). I am utilising DocumentFormat.OpenXML version 2.7.2 and the following code to load and change the Creator:

public static SetCreator(Stream inputStream, string newCreator)
{
    //the inputStream is actually a MemoryStream
    WordprocessingDocument document = WordprocessingDocument.Open(inputStream, true);
    document.PackageProperties.Creator = newCreator;
    document.Save();
    //on this point i expect the original stream to be replaced with the new one
}

The document is only available as stream as this thing is for a web application projects. However, when i tried to re-read the stream in debug mode, it seems the changes on the document instance is not persisted. Also, it does not fire any exception.

Edit: Further testing, using older DocumentFormat.OpenXML (version 2.0.50022. the WordprocessingDocument class did not have Save() method but instead have Close() method. tried to modify the code into the following and it works.. Still wondering the proper way on 2.7.2 though.

public static SetCreator(Stream inputStream, string newCreator)
{
    //the inputStream is actually a MemoryStream
    WordprocessingDocument document = WordprocessingDocument.Open(inputStream, true);
    document.PackageProperties.Creator = newCreator;
    document.Close(); //On older version, calling this will save it into memory stream without actually closing it.
}

Solution

  • can you try this :

    // Change MemoryStream by FileStream
    public static SetCreator(FileStream inputStream, string newCreator)
    {
        using (WordprocessingDocument document = WordprocessingDocument.Open(inputStream, true))
        {
            document.PackageProperties.Creator = newCreator;
            // You shouldn't need to do document.Save()
        }
    }
    
    // Main code
    path = "C:\myPath";
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        SetCreator(fs, "ME");
    }