Search code examples
asp.netdocxproperties-filenovacode-docx

Set docx properties using library .docx


How to set properties like title, author, subject for a file created with docx library for .net ?

docx


Solution

  • The DocX project that you provided appears to be able to easily access the metadata properties that you are referring to and can do so quite easily by using the CoreProperties property as seen below :

    // Load your Document
    var wordFile = Novacode.DocX.Load(@"your-docx-file-path");
    // Access Metadata properties
    var props = wordFile.CoreProperties;
    

    The issue here is that this collection of properties is read only, so you won't be able to easily change them. However, you may be able to take a look at what the values look like and attempt to add one manually :

    An Example of DocX Exposed Properties

    So if you wanted to update the title property (clearly named dc:title), you would simply need to add a new Core Property (via the AddCoreProperty() method) that matched that same name and then save the file to persist the changes :

    // Load your Document
    var wordFile = DocX.Load(@"your-docx-file-path");
    // Update Metadata
    wordFile.AddCoreProperty("dc:title", "Example Title");
    wordFile.Save();
    

    After doing this, you should be able to re-open the file and see that your changes reflected :

    Look the dc:title Attribute Changed!

    As you can see the dc:title property is now set to "Example Title" as per the example code above.