Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve MVID of an assembly from c#?

How to retrieve the module version identifier (MVID) of a .NET assembly using reflection in c#?

like image 618
Nestor Avatar asked Mar 03 '11 15:03

Nestor


2 Answers

Should be:

var myAssembly = Assembly.GetExecutingAssembly(); //or whatever
var mvid = myAssembly.ManifestModule.ModuleVersionID;

There can be other modules in an assembly, but the ManifestModule would be the one that "identifies" the assembly itself.

like image 139
KeithS Avatar answered Oct 05 '22 22:10

KeithS


Here's a sample that doesn't use Reflection to load the assembly but instead uses System.Reflection.Metadata:

using (var stream = File.OpenRead(filePath))
{
    PEReader reader = new PEReader(stream);
    var metadataReader = reader.GetMetadataReader();
    var mvidHandle = metadataReader.GetModuleDefinition().Mvid;
    var mvid = metadataReader.GetGuid(mvidHandle);
}

And here's a sample of using Mono.Cecil:

var module = Mono.Cecil.ModuleDefinition.ReadModule(filePath);
var mvid = module.Mvid;

And here's an example of a standalone code to read the MVID without any dependencies. It is a stripped-down version of Mono.Cecil in a single file: https://github.com/KirillOsenkov/MetadataTools/blob/master/src/PEFile/ImageReader.cs

like image 38
Kirill Osenkov Avatar answered Oct 05 '22 22:10

Kirill Osenkov