How do you extract the fully qualified assembly name from a qualified type assembly name?

I have a qualified type assembly name like

MyNamespace.MyClass, MyAssembly, Version = 1.0.0.0, Culture = Neutral, PublicKeyToken = Zero

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

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

Obviously, I could do this with a simple parsing of strings, but is there a structure method for this?

Note. I have no type or assembly, just a string, and this is an essential part of the problem, so myType.AssemblyQualifiedName, myType.Assembly.FullName, etc. will not help

+4
source share
3 answers

An overload in Type.GetType accepts a function that can be used to solve AssemblyName for assembly. A return value of null usually throws an exception, because the type cannot be resolved, but this can be suppressed by passing false to the throwOnError parameter.

The function used for resolution can also set a string variable in the outer scope returned by the source code.

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; } } } 
+2
source

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 do not have an assembly? Sorry to be the bearer of bad news, but then you need to make out.

+1
source

If you want to use GetType, you will need to load the assembly into the current domain. You can find out how to do it here .

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

0
source

All Articles