DEV Community

Gia
Gia

Posted on

How to Set Custom Properties for Word Documents in C#

Document properties are metadata used to describe and identify the characteristics and attributes of a document, typically classified as built-in properties and custom properties. This functionality plays an important role in the management and usage of documents. In addition to regular properties, users can also add custom properties or tags according to their own needs, enabling more flexible document organization and management, thus improving work efficiency. The passage will show you how to sett custom properties for Word in C# programmatically.

Tool:

  • Visual Studio 2022
  • Free Spire.Doc for .NET This is totally free library, which enables developers to create, edit or convert Word documents on .NET platforms easily.

Installation:

  1. Download and install Free Spire.Doc for .NET.
  2. Create a new C# project in Visual Studio and open it.
  3. Right-click " References " in the " Solution Explorer ".
  4. And then select " Add Reference " > " Browse ".
  5. Find the DLL file in the BIN folder under the installation path and click " OK " to add it as a reference.

Sample Codes:

After importing DLL files to your project, you can refer to the following codes to add custom properties to Word Documents.

C#

using Spire.Doc;
using System;

namespace CustomDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Add custom document properties to the document
            CustomDocumentProperties customProperties = document.CustomDocumentProperties;
            customProperties.Add("Document ID", 1);
            customProperties.Add("Authorized", true);
            customProperties.Add("Authorized By", "Sam");
            customProperties.Add("Authorized Date", DateTime.Today);

            //Save the result document
            document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • In the above code, a namespace named “CustomDocumentProperties” is first defined.
  • Within this namespace, create a class named “Program” as the entry point of the program.
  • In the main function “Main”, we create a “Document” object to represent an instance of a Word document.
  • Then, load a Word document by using the “LoadFromFile” method.
  • Next, obtain the “CustomDocumentProperties” object and use the “Add(string, object)” method to add custom properties to the document's custom property collection.
  • Finally, call the “SaveToFile” method to save the result document.

Image description

Top comments (0)