Search code examples
c#windows-property-system

How to set extended file properties?


I need to set the Company field value for some Word/PDF documents. I am talking about the extended file properties (summary/author/title, etc.) you see under File Properties.

I know how to get them (by using shell32.dll class library). I assumed that I could also set them with the same class library, but it seems like writing extended properties is a little bit more difficult and shell32.dll doesn't allow that.

I found something about taglib-sharp, which seems to have an option to set extended properties, but I don't really understand how it works.


Solution

  • Add following NuGet packages to your project:

    • Microsoft.WindowsAPICodePack-Shell by Microsoft
    • Microsoft.WindowsAPICodePack-Core by Microsoft

    Read and Write Properties

    using Microsoft.WindowsAPICodePack.Shell;
    using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
    
    string filePath = @"C:\temp\example.docx";
    var file = ShellFile.FromFilePath(filePath);
    
    // Read and Write:
    
    string[] oldAuthors = file.Properties.System.Author.Value;
    string oldTitle = file.Properties.System.Title.Value;
    
    file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
    file.Properties.System.Title.Value = "Example Title";
    
    // Alternate way to Write:
    
    ShellPropertyWriter propertyWriter =  file.Properties.GetPropertyWriter();
    propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
    propertyWriter.Close();
    

    Important:

    The file must be a valid one, created by the specific assigned software. Every file type has specific extended file properties and not all of them are writable.

    If you right-click a file on desktop and cannot edit a property, you wont be able to edit it in code too.

    Example:

    • Create txt file on desktop, rename its extension to docx. You can't edit its Author or Title property.
    • Open it with Word, edit and save it. Now you can.

    So just make sure to use some try catch

    Further Topic: MS Docs: Implementing Property Handlers