Ryan
Ryan

Reputation: 1340

Getting ANY extended file attribute in C#

I'm trying to find a way to get an Extended File Attribute (specifically, the "Product Version") on a COM DLL in C#. I found a few examples on MSDN on using the Shell32 from adding the "Microsoft Shell Controls and Automation" COM reference, but the documentation seems somewhat vague. Is there a simple way to do this?

For example: Take the following properties of C:\Windows\Notepad.exe:

Properties of Notepad.exe

I want to programatically get the "Product version" attribute in C#. By the way, this could be any file, however, I'm just using Notepad.exe because it's a generic example

Upvotes: 1

Views: 3100

Answers (3)

jac
jac

Reputation: 9726

.NET has built-in methods to do this.

MessageBox.Show("Notepad product version " + GetProductVersion("C:\\Windows\\notepad.exe"), "Product Version");

public string GetProductVersion(string fileName)
{
    System.Diagnostics.FileVersionInfo fileVersionInfo =
        System.Diagnostics.FileVersionInfo.GetVersionInfo(fileName);
    return fileVersionInfo.ProductVersion;
}

Result

Upvotes: 0

vcsjones
vcsjones

Reputation: 141588

Alternatively, you can use the FileVersionInfo class to do that in a single line:

Console.WriteLine(FileVersionInfo.GetVersionInfo(@"C:\Windows\notepad.exe").ProductVersion);

Upvotes: 5

Ryan
Ryan

Reputation: 1340

I came up with the following easy to use function that will return the value of any file property:

 public static string GetExtendedFileAttribute(string filePath, string propertyName)
    {
        string retValue = null;
        Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
        object shell = Activator.CreateInstance(shellAppType);
        Shell32.Folder folder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { @"C:\Windows\System32" });
        int? foundIdx = null;
        for (int i = 0; i < short.MaxValue; i++)
        {
            string header = folder.GetDetailsOf(null, i);
            if (header == propertyName)
            {
                foundIdx = i;
                break;
            }
        }

        if (foundIdx.HasValue)
        {
            foreach (FolderItem2 item in folder.Items())
            {
                if (item.Name.ToUpper() == System.IO.Path.GetFileName(filePath).ToUpper())
                {
                    retValue = folder.GetDetailsOf(item, foundIdx.GetValueOrDefault());
                    break;
                }
            }
        }


        return retValue;

    }

Here is an example of how it's called:

 static void Main(string[] args)
    {
        Console.WriteLine(GetExtendedFileAttribute(@"C:\Windows\Notepad.exe", "Product version"));   
        Console.ReadLine();
    }

Here is the output:

enter image description here

Upvotes: 2

Related Questions