31

I would like to parse an assembly qualified name in .NET 3.5. In particular, the assembly itself is not available, it's just the name. I can think of many ways of doing it by hand but I guess I might be missing some feature to do that in the system libraries. Any suggestion?

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
Joannes Vermorel
  • 8,976
  • 12
  • 64
  • 104

5 Answers5

20

The AssemblyName class can parse the assembly name for you, just pass in the string to its constructor. If you have an assembly qualified type name, I think you'll have to strip of the type part of the string first (ie everything up to the first comma).

Mattias S
  • 4,748
  • 2
  • 17
  • 18
  • 8
    Stripping the name is usually very complex. Consider even simple Tuple: "System.Tuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" – Yuri Astrakhan Jan 28 '12 at 00:39
  • 13
    AssemblyName constructor throws FileLoadException unless it's able to load the assembly – Ihar Bury Feb 08 '12 at 15:56
7

There is a parser implementation in Mono and BNF grammar on MSDN

Pavel Savara
  • 3,427
  • 1
  • 30
  • 35
6

From .Net 4 and on you have a new override for Type.GetType:

public static Type GetType(
    string typeName,
    Func<AssemblyName, Assembly> assemblyResolver,
    Func<Assembly, string, bool, Type> typeResolver,
    bool throwOnError,
    bool ignoreCase
)

See http://msdn.microsoft.com/en-us/library/ee332784%28v=vs.100%29.aspx

What you need to do is in the example of the above documentation:

Type t2 = Type.GetType(test,
            (aName) => aName.Name == "MyAssembly" ? 
                Assembly.LoadFrom(@".\MyPath\v5.0\MyAssembly.dll") : 
                Assembly.Load(aName),
            (assem, name, ignore) => assem == null ? 
                Type.GetType(name, false, ignore) : 
                assem.GetType(name, false, ignore), true
);

You may replace the above lambdas with more complex functions.

2

There is a class TypeIdentifier in Alphaleonis.Reflection.Metadata (also available from NuGet) that can parse an assembly qualified name (as well as a full type name or simple type name), and deconstruct it and allow modifications to it.

DeCaf
  • 6,026
  • 1
  • 29
  • 51
-3

If assembly loaded you can use something like that:

    Assembly assembly = Assembly.GetExecutingAssembly();
    string assemblyName = assembly.GetName().Name;

In the example above I used an executing assembly but you loop through your loaded assembly.

Update: You always can load an assembly in a separate AppDomain get the assembly name and after you are done, unload it. Let me know if you need a sample.

Vadim
  • 21,044
  • 18
  • 65
  • 101