如何设置扩展文件属性?

and*_*ree 41 c#

我需要为某些Word/PDF文档设置Company字段值.我在谈论你在文件属性下看到的扩展文件属性(摘要/作者/标题等).

我知道如何获得它们(通过使用shell32.dll类库).我假设我也可以使用相同的类库来设置它们,但是看起来编写扩展属性似乎有点困难并且shell32.dll不允许这样做.

我发现了一些东西taglib-sharp,似乎可以选择设置扩展属性,但我真的不明白它是如何工作的.

Mar*_*der 49

解决方案2016

将以下NuGet包添加到项目中:

  • Microsoft.WindowsAPICodePack-Shell 由微软
  • Microsoft.WindowsAPICodePack-Core 由微软

读写属性

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();
Run Code Online (Sandbox Code Playgroud)

重要:

该文件必须是有效的文件,由特定的已分配软件创建.每种文件类型都有特定的扩展文件属性,并非所有文件属性都是可写的.

如果右键单击桌面上的文件而无法编辑属性,则无法在代码中对其进行编辑.

例:

  • 在桌面上创建txt文件,将其扩展名重命名为docx.您不能编辑它AuthorTitle财产.
  • 用Word打开它,编辑并保存.现在你可以.

所以只要确保使用一些 try catch

进一步的主题: MSDN:实现属性处理程序

  • 这个答案需要更多+ 1.不能让它挂在底部.它不仅是OP的最佳答案,而且"WindowsAPICodePack"也很棒. (2认同)
  • 出于某种原因,`ShellPropertyWriter` 似乎不会_偶尔_保存更改。直接更改值 [如本答案所示](/sf/answers/3583208121/) 似乎对我来说效果更好。 (2认同)

and*_*ree 24

好的,这是我自己的问题的答案,因为我在这个论坛上找不到我的答案,它可能对其他人有用.解决方案是使用dsofile.dll和OleDocumentPropertiesClass.这是关于dsofile.dll的MS文章 - 链接 在这个链接中,您可以下载dsofile.dll和其他一些文件.但最有可能的是,就像我一样,你将面临一些难以找到解决方案的奇怪问题.

1)在输入dsofile.dll之后,您需要注册类:oped cmd并导航到目录的c:\ dsofile,在那里您已经解压缩了下载的dsofile.dll.之后 - 写行regsvr32 dsofile.dll.你应该得到一个消息框说注册成功.如果没有,最可能的是你没有管理员权限.如果您希望这样做,您将需要管理员权限.

2)在您的程序中尝试使用此类之后,如果您使用的是.NET 4.0,则可能会看到错误,例如"类无法嵌入..." 嗯,为此,右键单击dsofile in引用列表,属性 - >嵌入互操作文件 - >设置为FALSE.

3)使用方法:

    //creates new class of oledocumentproperties
    var doc = new OleDocumentPropertiesClass();

    //open your selected file
    doc.Open(pathToFile, false, dsoFileOpenOptions.dsoOptionDefault);

    //you can set properties with summaryproperties.nameOfProperty = value; for example
    doc.SummaryProperties.Company = "lol";
    doc.SummaryProperties.Author = "me";

    //after making changes, you need to use this line to save them
    doc.Save();
Run Code Online (Sandbox Code Playgroud)

  • 如果我没记错的话 - 这只适用于Office文件.对于PDF,还有其他库提供此功能. (3认同)

Mar*_*age 7

Windows资源管理器(使用shell32.dll)能够显示扩展属性,因为它了解许多不同的文件格式并可以解析这些格式.但是,要设置扩展属性,您可能需要特定于文件格式的库.例如,设置MP3文件文件的作者与设置Office文档的作者相比是非常不同的.(实际上,Windows资源管理器允许您在Office文档上设置一些扩展属性.)

taglib-sharp仅适用于媒体文件,很可能无法设置任何其他类型文件的扩展属性.

您需要的是一个库或工具,您可以自动修改PDF文件.你可以尝试google pdf sdk.如果您还需要使用Word文件,则可以使用COM自动化来自动化Word.根据所使用的Word文件格式,您也可以直接使用该文件而无需安装Word(XML比旧的二进制"流"格式更容易).