从.NET程序集中获取ProgID

时间:2009-04-10 20:04:40

标签: .net reflection com .net-2.0

我想编写一个程序来查找所有com可见的.NET类,以及它们来自.NET程序集的ProgID。最好的方法是什么?

1 个答案:

答案 0 :(得分:7)

这将获得ProgId而不是ClassId,并且如果整个程序集被标记为可见,也可以工作:

        Assembly assembly = Assembly.LoadFile("someassembly.dll");

        bool defaultVisibility;
        object[] assemblyAttributes = assembly.GetCustomAttributes(typeof(ComVisibleAttribute),false);
        if (assemblyAttributes.Length == 0)
            defaultVisibility = false;
        else
            defaultVisibility = (assemblyAttributes[0] as ComVisibleAttribute).Value;

        foreach(Type type in assembly.GetTypes())
        {
            bool isComVisible = defaultVisibility;
            object []attributes = type.GetCustomAttributes(typeof(ComVisibleAttribute),true);
            if (attributes.Length > 0)
                isComVisible = (attributes[0] as ComVisibleAttribute).Value;
            if (isComVisible)
            {
                attributes = type.GetCustomAttributes(typeof(ProgIdAttribute),true);
                if (attributes.Length >0)
                {
                    Console.WriteLine(String.Format("Type {0} has ProgID {1}",type.Name,(attributes[0] as ProgIdAttribute).Value));
                }
            }
        }