代码之家  ›  专栏  ›  技术社区  ›  C. Ross trotttrotttrott

从.NET程序集获取ProgID

  •  4
  • C. Ross trotttrotttrott  · 技术社区  · 15 年前

    我想编写一个程序,从.NET程序集中查找所有COM可见的.NET类及其ProgID。最好的方法是什么?

    1 回复  |  直到 11 年前
        1
  •  7
  •   Darren Clark    15 年前

    这将得到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));
                    }
                }
            }