Read/Write 'Extended' file properties (C#)

后端 未结 10 2238
我在风中等你
我在风中等你 2020-11-22 02:54

I\'m trying to find out how to read/write to the extended file properties in C# e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer. An

10条回答
  •  旧时难觅i
    2020-11-22 03:46

    Solution 2016

    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: MSDN: Implementing Property Handlers

提交回复
热议问题