How to extract assembly name from DLL file in C#

There are situations where you have a DLL file/s in a project that does not necessarily have the same name or you are downloading that DLL file/s from a third party or other sources that are not necessary again to have the same name.

For this reason, I renamed Newtonsoft.Json.dll to 6b9aeacd-0521-444b-a5eb-a8c58b065c6e.dll and put it up on my blog.

Now let’s download the file:

var baseDirectory = @"D:\project\dlls";
var link = "https://itbackyard.com/others/download/6b9aeacd-0521-444b-a5eb-a8c58b065c6e.dll";
var uri = new Uri(link);
var fileName = Path.GetFileName(uri.LocalPath);
var path = Path.Combine(baseDirectory, fileName);

if (!new FileInfo(path).Exists)
{
    HttpClient client = new HttpClient();
    var response = await client.GetAsync(uri);
    await using var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite);
    await response.Content.CopyToAsync(fs);
}

Now let’s extract the original assembly name of the file which is Newtonsoft.Json.dll. This can be done in 2 ways.

One way is by loading the file as an Assembly object which is part of System.Reflection and the other is by using the FileVersionInfo object which is part of System.Diagnostics.

Let’s take the Assembly object way:

Assembly dll = Assembly.LoadFile(path);
var dllName = dll.ManifestModule.ScopeName;
Console.WriteLine(dllName);

This will output Newtonsoft.Json.dll.

Now let’s take the FileVersionInfo way:

FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(path);
var dllName = fileVersionInfo.OriginalFilename;
Console.WriteLine(dllName);

This will output Newtonsoft.Json.dll.

Both can extract assembly names but each of them has its own use cases. For example, Assembly has ExportedTypes that give a list of all types inside Nettonsoft.Json.dll and more features, whereas FileVersionInfo has file features.

Read more about:

Leave a Comment