R – How to extract an assembly full name from the assembly qualified name of a type

assembliesnetreflectiontypes

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

MyNamespace.MyClass, MyAssembly,
Version=1.0.0.0, 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

Best Answer

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