我们在编程时候,有时候要得到SDK运行时的所在目录。
请看下面:
[Flags]
private enum RuntimeInfo : uint
{
UpgradeVersion = 0x1, // RUNTIME_INFO_UPGRADE_VERSION
RequestIA64 = 0x2, // RUNTIME_INFO_REQUEST_IA64
RequestAmd64 = 0x4, // RUNTIME_INFO_REQUEST_AMD64
RequestX86 = 0x8, // RUNTIME_INFO_REQUEST_X86
DoNotReturnDirectory = 0x10, // RUNTIME_INFO_DONT_RETURN_DIRECTORY
DoNotReturnVersion = 0x20, // RUNTIME_INFO_DONT_RETURN_VERSION
DoNotShowErrorDialog = 0x40 // RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG
}
[DllImport("mscoree.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = false)]
private static extern int /* [HRESULT] */ GetRequestedRuntimeInfo(
string /* [LPCWSTR] */ pExe,
string /* [LPCWSTR] */ pwszVersion,
string /* [LPCWSTR] */ pConfigurationFile,
uint /* [DWORD] */ startupFlags,
RuntimeInfo /* [DWORD] */ runtimeInfoFlags,
StringBuilder /* [LPWSTR] */ pDirectory,
uint /* [DWORD] */ dwDirectory,
out uint /* [DWORD *] */ dwDirectoryLength,
StringBuilder /* [LPWSTR] */ pVersion,
uint /* [DWORD] */ cchBuffer,
out uint /* [DWORD *] */ dwLength
);
/// <summary>
/// Returns the installation directory of the specified .NET runtime.
/// </summary>
/// <param name="version">
/// The version of the runtime.
/// </param>
/// <param name="upgradeVersion">
/// True to return the installation directory of the nearest compatible runtime version, or false for an exact match.
/// </param>
/// <returns>
/// The .NET runtime installation directory.
/// </returns>
private static string GetRuntimeInstallationDirectory(Version version, bool upgradeVersion)
{
string versionString = "v" + version.ToString(3);
RuntimeInfo runtimeInfo = RuntimeInfo.DoNotShowErrorDialog;
if (upgradeVersion)
runtimeInfo |= RuntimeInfo.UpgradeVersion;
StringBuilder runtimeDirectory = new StringBuilder(270);
StringBuilder runtimeVersion = new StringBuilder("v65535.65535.65535".Length);
uint runtimeDirectoryLength;
uint runtimeVersionLength;
int errorCode = GetRequestedRuntimeInfo(null, versionString, null, 0, runtimeInfo, runtimeDirectory, (uint)runtimeDirectory.Capacity, out runtimeDirectoryLength, runtimeVersion, (uint)runtimeVersion.Capacity, out runtimeVersionLength);
Marshal.ThrowExceptionForHR(errorCode);
return Path.Combine(runtimeDirectory.ToString(), runtimeVersion.ToString());
}
样例可以是:
Version version = new Version(2, 0, 50727);
GetRuntimeInstallationDirectory(version, true) ;