我最近需要做这个,所以我在互联网上搜索了所有可能的 Windows SDK 路径,并按照最近已知的顺序进行了搜索。我还检查操作系统和进程是否为 64 位,然后只需查找相应的 Program Files 文件夹中的版本即可。我认为,在工具的 32 位版本和 64 位版本之间选择 64 位版本并没有任何重大意义。ILAsm 的 x86 版本可以轻松地组装 64 位优先的程序集,而且它全部都是 IL,实际上并没有执行任何代码。
ILDasm 是 Windows SDK 的一部分,而 ILAsm 只是 .NET Framework SDK,所以这里有一些静态方法来寻找它们。该代码适用于 .NET 4.0,但如果您愿意,可以进行一些小的调整以使其在 .NET 2.0 上构建。
// ILDasm.exe will be somewhere in here
private static string FindPathForWindowsSdk()
{
string[] windowsSdkPaths = new[]
{
@"Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\",
@"Microsoft SDKs\Windows\v8.0A\bin\",
@"Microsoft SDKs\Windows\v8.0\bin\NETFX 4.0 Tools\",
@"Microsoft SDKs\Windows\v8.0\bin\",
@"Microsoft SDKs\Windows\v7.1A\bin\NETFX 4.0 Tools\",
@"Microsoft SDKs\Windows\v7.1A\bin\",
@"Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\",
@"Microsoft SDKs\Windows\v7.0A\bin\",
@"Microsoft SDKs\Windows\v6.1A\bin\",
@"Microsoft SDKs\Windows\v6.0A\bin\",
@"Microsoft SDKs\Windows\v6.0\bin\",
@"Microsoft.NET\FrameworkSDK\bin"
};
foreach (var possiblePath in windowsSdkPaths)
{
string fullPath = string.Empty;
// Check alternate program file paths as well as 64-bit versions.
if (Environment.Is64BitProcess)
{
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), possiblePath, "x64");
if (Directory.Exists(fullPath))
{
return fullPath;
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), possiblePath, "x64");
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
// ILAsm.exe will be somewhere in here
private static string FindPathForDotNetFramework()
{
string[] frameworkPaths = new[]
{
@"Microsoft.NET\Framework\v4.0.30319",
@"Microsoft.NET\Framework\v2.0.50727"
};
foreach (var possiblePath in frameworkPaths)
{
string fullPath = string.Empty;
if (Environment.Is64BitProcess)
{
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), possiblePath.Replace(@"\Framework\", @"\Framework64\"));
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
您可以通过传入您要查找的可执行文件并将 Directory.Exists 更改为 File.Exists 来增强此功能,这取决于您。您还可以将可能的列表放在配置文件中,以便在不重新编译的情况下添加更多内容。