4
votes

Does C# (or Windows) provide a way of getting the location of the directory that contains the .NET reference assemblies for a given version of .NET? On my machine, they are located at:

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

Where ### is any of 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, or 4.6.1. These directories contains mscorlib and some System assemblies, and the v4.5+ ones also have some more System assemblies in the Facades\ subdirectory.

Is there a better way of obtaining the path of these directories than hardcoding it? (Or, alternatively, is Microsoft committed to keeping the reference assemblies in the same place so that hardcoding it won't break?)

(Context: I'm using Roslyn to compile a project, and it isn't picking up on any of the assemblies referenced in my csproj, framework or otherwise - so I'm loading them manually as metadata references instead. The directory I identified above is where MSBuild is getting the assemblies from when it runs csc, so I figure I should get the assemblies from there too.)

4

4 Answers

3
votes

Use the ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies method from Microsoft.Build.Utilities.Core:

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

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

ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.VersionLatest);
1
votes

If you check Microsoft's MSBuild source code at GitHub, you can read FrameworkLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies to understand the logic.

-1
votes

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()