开发者

How do you extract an assembly full name from the assembly qualified name of a type?

I have an assembly qualified name of a type, e.g.

MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, 开发者_StackOverflow社区Culture=neutral, PublicKeyToken=null

I want to extract the assembly full name, i.e.

MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Obviously I could do this with simple string parsing, but is there a framework method for doing this?

Note: I don't have the type or assembly, just the string, and this is an essential part of the problem, so myType.AssemblyQualifiedName, myType.Assembly.FullName, etc isn't going to help


An overload to Type.GetType accepts an function that can be used to resolve the AssemblyName to an assembly. Returning null would normally throw an exception since the type cannot be resolved, but this can be suppressed by passing false to the throwOnError parameter.

The function used to resolve can also set a string variable in the outer scope that the original code will return.

using System;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApp {
    public static class Program {
        public static void Main() {
            var assemblyName = GetAssemblyName("MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            Debug.Assert(assemblyName == "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
        }

        public static String GetAssemblyName(String typeName) {
            String assemblyName = null;
            Func<AssemblyName, Assembly> assemblyResolver = name => {
                assemblyName = name.FullName;
                return null;
            };

            var type = Type.GetType(typeName, assemblyResolver, null, false);
            if (type != null)
                return type.AssemblyQualifiedName;

            return assemblyName;
        }
    }
}


Here:

public string AssemblyName(string assemblyQualifiedName) {
    Type type = Type.GetType(assemblyQualifiedName, false);
    if(type == null) {
         return Parse(assemblyQualifiedName);
    }
    return type.Assembly.Name;
}

Edit: Wait. You don't have the assembly? Sorry to be the bearer of bad news, but then you need to parse.


If you want to use GetType you'll need to load the assembly to the current domain. You can learn how to do it here.

Although it seems like a lot of work just to avoid trivial parsing...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜