如何在不进行硬编码的情况下获取存储 .NET 引用程序集的目录路径?

How do I get the paths of the directories where .NET reference assemblies are stored, without hardcoding?

C#(或 Windows)是否提供了一种获取目录位置的方法,该目录包含给定版本的 .NET 的 .NET 参考程序集?在我的机器上,它们位于:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v###\

其中 ### 是 3.5、4.0、4.5、4.5.1、4.5.2、4.6 或 4.6.1 中的任何一个。这些目录包含 mscorlib 和一些 System 程序集,而 v4.5+ 的 Facades\ 子目录中还有一些 System 程序集。

有没有比硬编码更好的获取这些目录路径的方法? (或者,或者,Microsoft 是否承诺将参考程序集保留在同一位置,以便硬编码不会中断?)

(上下文:我正在使用 Roslyn 编译一个项目,它没有在我的 csproj、框架或其他地方引用的任何程序集上获取 - 所以我将它们手动加载为元数据引用. 我在上面确定的目录是 MSBuild 在运行时从中获取程序集的位置 csc,所以我想我也应该从那里获取程序集。)

Getting the .NET Framework directory path:

The path to the installation directory of the CLR active for the current .NET application can be obtained by using the following method:

System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()

使用 Microsoft.Build.Utilities.Core 中的 ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies 方法:

foreach (TargetDotNetFrameworkVersion version in Enum.GetValues(typeof(TargetDotNetFrameworkVersion)))
{
    string location = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(version);
    Console.WriteLine($"{version}: {location}");
}

GetPathToDotNetFrameworkReferenceAssemblies returns "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\version\".

ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.VersionLatest);

如果您在 GitHub 查看 Microsoft 的 MSBuild 源代码,您可以阅读 FrameworkLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies 以了解其中的逻辑。