Guaranteed way to find the filepath of the ildasm.exe and ilasm.exe files regardless of .NET version/environment?

myermian picture myermian · Nov 28, 2012 · Viewed 15.9k times · Source

Is there a way to programmatically get the FileInfo/Path of the ildasm.exe/ilasm.exe executables? I'm attempting to decompile and recompile a dll/exe file appropriately after making some alterations to it (I'm guessing PostSharp does something similar to alter the IL after the compilation).

I found a blog post that pointed to:

var pfDir = Environment.GetFolderPath(Environment.SpecialFolders.ProgramFiles));
var sdkDir = Path.Combine(pfDir, @"Microsoft SDKs\Windows\v6.0A\bin");

...

However, when I ran this code the directory did not exist (mainly because my SDK version is 7.1), so on my local machine the correct path is @"Microsoft SDKs\Windows\v7.1\bin". How do I ensure I can actually find the ildasm.exe?

Similarly, I found another blog post on how to get access to ilasm.exe as:

string windows = Environment.GetFolderPath(Environment.SpecialFolder.System);
string fwork = Path.Combine(windows, @"..\Microsoft.NET\Framework\v2.0.50727");

...

While this works, I noticed that I have Framework and Framework64, and within Framework itself I have all of the versions up to v4.0.30319 (same with Framework64). So, how do I know which one to use? Should it be based on the .NET Framework version I'm targetting?

Summary:

  • How do I appropriately guarantee to find the correct path to ildasm.exe?
  • How do I appropriately select the correct ilasm.exe to compile?

Answer

joshcomley picture joshcomley · Feb 15, 2015

One option would be to reference Microsoft.Build.Utilities.Core and use:

var ildasm = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("ildasm.exe", TargetDotNetFrameworkVersion.VersionLatest);
var ilasm = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkFile("ilasm.exe", TargetDotNetFrameworkVersion.VersionLatest);

Right now on my machine this returns:

ildasm = C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\ildasm.exe

ilasm = C:\Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe