获取 .NET Framework 目录路径
如何获取 C# 应用程序内的 .NET Framework 目录路径?
我指的文件夹是“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727”
How can I obtain the .NET Framework directory path inside my C# application?
The folder that I refer is "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可以使用以下方法获取当前 .NET 应用程序的 CLR 活动安装目录的路径:
我强烈建议不要直接读取注册表。 例如,当 .NET 应用程序在 64 位系统中运行时,可以从“C:\Windows\Microsoft.NET\Framework64\v2.0.50727”(任何 CPU、x64 编译目标)或“C:\ Windows\Microsoft.NET\Framework\v2.0.50727”(x86 编译目标)。 读取注册表不会告诉您当前 CLR 使用了两个目录中的哪一个。
另一个重要事实是,对于 .NET 2.0、.NET 3.0 和 .NET 3.5 应用程序,“当前的 CLR”将是“2.0”。 这意味着即使在 .NET 3.5 应用程序(从 3.5 目录加载某些程序集)中,GetRuntimeDirectory() 调用也将返回 2.0 目录。 根据您对术语“.NET Framework 目录路径”的解释,GetRuntimeDirectory 可能不是您要查找的信息(“CLR 目录”与“3.5 程序集所在的目录”)。
The path to the installation directory of the CLR active for the current .NET application can be obtained by using the following method:
I would strongly advice against reading the registry directly. For example, when a .NET application is running in 64bit systems, the CLR can either be loaded from "C:\Windows\Microsoft.NET\Framework64\v2.0.50727" (AnyCPU, x64 compilation targets) or from "C:\Windows\Microsoft.NET\Framework\v2.0.50727" (x86 compilation target). Reading registry will not tell you which one of the two directories was used by the current CLR.
Another important fact is that "the current CLR" will be "2.0" for .NET 2.0, .NET 3.0 and .NET 3.5 applications. This means that the GetRuntimeDirectory() call will return 2.0 directory even within .NET 3.5 applications (that load some of their assemblies from 3.5 directory). Depending on your interpretation of the term ".NET Framework directory path", GetRuntimeDirectory might not be the information you are looking for ("CLR directory" versus "directory from which 3.5 assemblies are coming from").
一种更简单的方法是包含 Microsoft.Build.Utilities 程序集并使用
An easier way is to include the Microsoft.Build.Utilities assembly and use
您可以从 Windows 注册表中获取它:
// ...
来源
You can grab it from the Windows Registry:
// ...
Source
对于 .NET Framework 版本 >= 4.5,来自 MSDN 的官方方式:
For .NET Framework versions >= 4.5, an official way from MSDN:
读取[HKLM]\Software\Microsoft.NetFramework\InstallRoot键的值 - 您将得到“C:\WINDOWS\Microsoft.NET\Framework”。 然后附加所需的框架版本。
Read value of the [HKLM]\Software\Microsoft.NetFramework\InstallRoot key - you will get "C:\WINDOWS\Microsoft.NET\Framework". Then append with desired framework version.