Add new metadata properties to a file

2019-01-22 08:40发布

I want to add some metadata properties to some files. Just like there are Owner, Computer, Title, Subject, etc for doc files, I want to be able to add some custom attributes. How can that be done?

1条回答
甜甜的少女心
2楼-- · 2019-01-22 09:07

As already mentioned it depends on the filesystem. So this will only work with NTFS.

One way is creating ADS streams: See the edit history.

Another way is using the DSOFile-Library, which is intended to work on Office files only. But it works on every file.

First of all download the library here (x64+x86): DOWNLOAD

IMPORTANT: Since DSO OLE is 32bit DLL it will only work, when you set your compilation target CPU to x86. Otherwise it will throw an Exception. There's also a 64bit version avaliable: How to read custom file properties in c#

Then create a refernce to the COM DLL in your project (Right click on the solution -> Add reference -> COM tab -> Add "DSO OLE Document Property Reader v2.1") and use the namespace:

using DSOFile;

After that you can create your own attributes:

First of all open the file:

OleDocumentProperties myFile = new DSOFile.OleDocumentProperties();
myFile.Open(@"MYPATHHERE", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);

Create a object for yourValue: object yourValue = "Your Value";

Then check if there's already a property like the one you want to create:

foreach (DSOFile.CustomProperty property in myFile.CustomProperties)
{
   if (property.Name == "Your Property Name"){
      //Property exists
      //End the task here (return;) oder edit the property
      property.set_Value(yourValue);
   }
}

Then after checking for existing attributes, you can add the attribute:

myFile.CustomProperties.Add("Your Property Name", ref yourValue);

To finish the task, save and close the file:

myFile.Save();
myFile.Close(true);

You can download a sample project on my homepage.

Now to the part of showing the attributes in the explorer.

You have to create a shell extension for that. For more info on that, visit the Codeproject page.

I created one, you can download it here. But you have to sign it again (look for a "how-to" on the mentioned page).

It will look like that, when right-clicking on a .css/.js/.txt-file: Shell extension with Sharpshell
Or create your own properties tab:
CustomPropertiesTab
You can download the sample here: DOWNLOAD

For more information about Dsofile.dll and other source see Microsoft Dsofile.dll

查看更多
登录 后发表回答