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

时间:2008-10-20 21:56:11

标签: c# extended-properties

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

10 个答案:

答案 0 :(得分:78)

对于那些对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)}");
        }
    }
}

答案 1 :(得分:27)

ID3阅读器有a CodeProject article。还有一个thread at kixtart.org,其中包含其他属性的更多信息。基本上,您需要调用文件夹 shell对象上的GetDetailsOf() method shell32.dll

答案 2 :(得分:24)

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控件和自动化的引用。

答案 3 :(得分:23)

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

进一步的主题: MSDN: Implementing Property Handlers

答案 4 :(得分:8)

谢谢你们这个帖子!当我想弄清楚exe的文件版本时,它帮助了我。但是,我需要自己弄清楚所谓的扩展属性。

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

对此的解决方案是属性索引器FolderItem.ExtendedProperty,如果删除属性名称中的所有空格,您将获得该值。例如。文件版本进入FileVersion,你就可以了。

希望这可以帮助其他人,只是想我会将此信息添加到此主题中。干杯!

答案 5 :(得分:8)

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

答案 6 :(得分:4)

Jerker's answer 稍微简单一些。这里的示例代码有效from 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.
}

答案 7 :(得分:3)

  • 在此线程和其他地方查看了许多解决方案之后 以下代码放在一起。这只是为了阅读一处房产。
  • 我无法得到 Shell32.FolderItem2.ExtendedProperty函数工作,应该是 获取字符串值并返回正确的值并为其键入 property ...对我来说总是空的,开发人员参考资源非常薄。
  • 似乎是WindowsApiCodePack 已经被微软放弃了,它给我们带来了以下代码。

使用:

string propertyValue = GetExtendedFileProperty("c:\\temp\\FileNameYouWant.ext","PropertyYouWant");
  1. 将返回您想要的扩展属性的值 给定文件和属性名称的字符串。
  2. 只有循环才能找到指定的属性 - 直到找到 发现所有属性就像一些示例代码
  3. 适用于Windows Server 2008等Windows版本,如果只是尝试正常创建Shell32对象,您将收到错误"Unable to cast COM object of type 'System.__ComObject' to interface type '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;
    }
    

答案 8 :(得分:1)

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

编辑:我已经更新了taglib sharp的链接。旧链接不再有效。

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

答案 9 :(得分:1)

这是一种基于我在本页和help with shell32 objects上找到的内容的读取(而不是写入)扩展属性的解决方案。

要清楚,这是一个hack。该代码看起来仍将在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相关的异常,则可以在此处找到解决方案:

Exception when using Shell32 to get File extended properties

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

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

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

最后,我发布了一种使用WindowsAPICodePack there

的更好的解决方案