While extending the Visual Studio SharePoint development tools you might be working on an extension that would be using the fully qualified (4-part) name of an assembly. It could be for example a custom Deployment Step or a MSBuild Task.

Code

In most scenarios you might be considering using the following code to get the fully qualified name of an assembly:

Assembly assembly = Assembly.LoadFrom(@"C:\MyAssembly.dll");
string name = assembly.FullName;

While it does the job, the above approach has a serious drawback. What it does is, it loads the assembly in the current AppDomain what locks it from further processing. As there is no way to unload an assembly from the current AppDomain, the code above makes it impossible to allow the assembly to be further processed by for example the build or the packaging process.

A better way to get the fully qualified name of an assembly is to use the AssemblyName class:

AssemblyName assemblyName = AssemblyName.GetAssemblyName(@"C:\MyAssembly.dll");
string name = assemblyName.FullName;

This approach doesn’t load the assembly into to the AppDomain and allows other processes to access the assembly as well.

If the assembly isn’t signed, the FullName property will return the following result:

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

If you don’t want to return 4-part names for non-signed assemblies, you can use the AssemblyName.Name property instead which will return MyAssembly only. You could easily wrap this all up in the following method:

public static string GetAssemblyName(string assemblyFile)
{
    AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyFile);
    return assemblyName.GetPublicKeyToken().Length == 0 ? assemblyName.Name : assemblyName.FullName;
}