读/写“扩展”文件属性 (C#)

本文关键字:文件属性 扩展 | 更新日期: 2023-09-27 17:47:21

我正在尝试找出如何在 C# 中读取/写入扩展文件属性例如,您可以在Windows资源管理器中看到的评论,比特率,访问日期,类别等。任何想法如何做到这一点?编辑:我将主要读取/写入视频文件(AVI/DIVX/...)

读/写“扩展”文件属性 (C#)

对于那些对VB不疯狂的人来说,这里是c#:

请注意,您必须从"引用"对话框的"COM "选项卡中添加对Microsoft Shell 控件和自动化的引用。

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();
    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;
    objFolder = shell.NameSpace(@"C:'temp'testprop");
    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }
    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}'t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

解决方案 2016

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

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

读取和写入属性

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();

重要:

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

如果在桌面上右键单击某个文件,但无法编辑属性,则也无法在代码中对其进行编辑。

例:

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

因此,请确保使用一些try catch

更多主题:Microsoft 文档:实现属性处理程序

有一篇针对 ID3 阅读器的 CodeProject 文章。 以及 kixtart.org 的线程,其中包含有关其他属性的更多信息。基本上,您需要在文件夹外壳对象上调用GetDetailsOf()方法进行shell32.dll

此示例在

VB.NET 读取所有扩展属性:

Sub Main()
        Dim arrHeaders(35)
        Dim shell As New Shell32.Shell
        Dim objFolder As Shell32.Folder
        objFolder = shell.NameSpace("C:'tmp")
        For i = 0 To 34
            arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
        Next
        For Each strFileName In objfolder.Items
            For i = 0 To 34
                Console.WriteLine(i & vbTab & arrHeaders(i) & ": " & objfolder.GetDetailsOf(strFileName, i))
            Next
        Next
    End Sub

您必须从"引用"对话框的"COM "选项卡中添加对Microsoft Shell 控件和自动化的引用。

谢谢你们的这个线程!当我想找出exe的文件版本时,它帮助了我。但是,我需要自己弄清楚所谓的扩展属性的最后一点。

如果在 Windows 资源管理器中打开 exe(或 dll)文件的属性,则会获得"版本"选项卡和该文件的扩展属性视图。我想访问其中一个值。

解决方案是属性索引器 FolderItem.ExtendedProperty,如果删除属性名称中的所有空格,则会获得该值。 例如,文件版本转到文件版本,你就有了它。

希望这对其他人有所帮助,只是想我会将此信息添加到此线程中。干杯!

GetDetailsOf()方法 - 检索有关文件夹中项目的详细信息。例如,其大小、类型或上次修改的时间。文件属性可能因Windows-OS版本而异。

List<string> arrHeaders = new List<string>();
 Shell shell = new ShellClass();
 Folder rFolder = shell.NameSpace(_rootPath);
 FolderItem rFiles = rFolder.ParseName(filename);
 for (int i = 0; i < short.MaxValue; i++)
 {
      string value = rFolder.GetDetailsOf(rFiles, i).Trim();
      arrHeaders.Add(value);
 }

Jerker的答案要简单一点。这是从MS工作的示例代码:

var folder = new Shell().NameSpace(folderPath);
foreach (FolderItem2 item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}

对于那些不能静态引用 shell32 的人,你可以像这样动态调用它:

var shellAppType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellApp = Activator.CreateInstance(shellAppType);
var folder = shellApp.NameSpace(folderPath);
foreach (var item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}
  • 在此线程和其他地方查看了许多解决方案以下代码放在一起。这仅用于读取属性。
  • 我无法得到Shell32.FolderItem2.ExtendedProperty函数工作,它应该获取字符串值并为其返回正确的值和类型财产。。。这对我来说总是空的,开发人员参考资源非常稀少。
  • WindowsApiCodePack似乎被Microsoft抛弃了,这给我们带来了下面的代码。

用:

string propertyValue = GetExtendedFileProperty("c:''temp''FileNameYouWant.ext","PropertyYouWant");
  1. 将返回所需的扩展属性的值作为给定文件和属性名称的字符串。
  2. 仅在找到指定属性之前循环 - 直到所有属性都像一些示例代码一样被发现
  3. 适用于Windows版本,如Windows server 2008,如果只是尝试正常创建Shell32对象,您将收到错误"无法将类型'System.__ComObject'的COM对象转换为接口类型'Shell32.Shell'"。

    public static string GetExtendedFileProperty(string filePath, string propertyName)
    {
        string value = string.Empty;
        string baseFolder = Path.GetDirectoryName(filePath);
        string fileName = Path.GetFileName(filePath);
        //Method to load and execute the Shell object for Windows server 8 environment otherwise you get "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'"
        Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
        Object shell = Activator.CreateInstance(shellAppType);
        Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });
        //Parsename will find the specific file I'm looking for in the Shell32.Folder object
        Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);
        if (folderitem != null)
        {
            for (int i = 0; i < short.MaxValue; i++)
            {
                //Get the property name for property index i
                string property = shellFolder.GetDetailsOf(null, i);
                //Will be empty when all possible properties has been looped through, break out of loop
                if (String.IsNullOrEmpty(property)) break;
                //Skip to next property if this is not the specified property
                if (property != propertyName) continue;    
                //Read value of property
                value = shellFolder.GetDetailsOf(folderitem, i);
            }
        }
        //returns string.Empty if no value was found for the specified property
        return value;
    }
    

这是一个基于我在此页面上找到的扩展属性以及 shell32 对象的帮助来读取 - 而不是写入 - 扩展属性的解决方案。

需要明确的是,这是一个黑客。看起来这段代码仍然可以在 Windows 10 上运行,但会命中一些空属性。以前版本的 Windows 应使用:

        var i = 0;
        while (true)
        {
            ...
            if (String.IsNullOrEmpty(header)) break;
            ...
            i++;

在 Windows 10 上,我们假设大约有 320 个属性需要读取,只需跳过空条目:

    private Dictionary<string, string> GetExtendedProperties(string filePath)
    {
        var directory = Path.GetDirectoryName(filePath);
        var shell = new Shell32.Shell();
        var shellFolder = shell.NameSpace(directory);
        var fileName = Path.GetFileName(filePath);
        var folderitem = shellFolder.ParseName(fileName);
        var dictionary = new Dictionary<string, string>();
        var i = -1;
        while (++i < 320)
        {
            var header = shellFolder.GetDetailsOf(null, i);
            if (String.IsNullOrEmpty(header)) continue;
            var value = shellFolder.GetDetailsOf(folderitem, i);
            if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);
            Console.WriteLine(header +": " + value);
        }
        Marshal.ReleaseComObject(shell);
        Marshal.ReleaseComObject(shellFolder);
        return dictionary;
    }

如前所述,您需要引用 Com 程序集 Interop.Shell32。

如果遇到与 STA 相关的异常,您将在此处找到解决方案:

使用 Shell32 获取文件扩展属性时出现异常

我不知道这些属性名称在外部系统上会是什么样子,并且找不到有关使用哪些可本地化常量来访问字典的信息。我还发现,并非"属性"对话框中的所有属性都存在于返回的字典中。

顺便说一句,这非常慢,而且 - 至少在 Windows 10 上 - 解析检索到的字符串中的日期将是一个挑战,因此使用它似乎是一个坏主意。

在Windows 10上,您绝对应该使用Windows.Storage库,其中包含SystemPhotoProperties,SystemMusicProperties等。https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties

最后,我在那里发布了一个更好的解决方案,它使用WindowsAPICodePack

我不确定您要尝试为哪种类型的文件编写属性,但 taglib-sharp 是一个出色的开源标记库,可以很好地包装所有这些功能。 它对大多数流行的媒体文件类型有很多内置支持,但也允许您对几乎任何文件进行更高级的标记。

编辑:我已经更新了指向标签库锐利的链接。 旧链接不再有效。

编辑:根据kzu的评论再次更新了链接。