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

后端 未结 10 2237
我在风中等你
我在风中等你 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:36

    Here is a solution for reading - not writing - the extended properties based on what I found on this page and at help with shell32 objects.

    To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:

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

    On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:

        private Dictionary 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();
            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;
        }
    

    As mentioned you need to reference the Com assembly Interop.Shell32.

    If you get an STA related exception, you will find the solution here:

    Exception when using Shell32 to get File extended properties

    I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.

    BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.

    On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc. https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties

    And finally, I posted a much better solution that uses WindowsAPICodePack there

提交回复
热议问题