从.NET程序集获取ProgID

4

我希望写一个程序来查找.NET程序集中所有可见的COM类以及它们的ProgID。你认为最好的方法是什么?

1个回答

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

谢谢,我漏掉了关于整个程序集是否标记为com可见的那一部分。 - C. Ross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接