从 .NET Standard 库中获取 Windows 系统目录

Get the Windows system directory from a .NET Standard library

似乎是个简单的问题,但 Google 似乎没有答案。

在 .NET Framework 中,我们可以使用 Environment.SystemDirectory 来获取系统目录(看起来类似于 C:\WINDOWS\System32),但是 属性 在当前版本中不存在.NET Standard 或 .NET Core。有没有办法在 .NET Standard(或失败,.NET Core)库中获取该文件夹?

出于我的目的,不需要调用 return 在非 Windows 平台上有用的东西(无论如何它 return 会是什么?/lib/usr/lib? 等),虽然我想如果这样做会很酷。

现在看来我最好的选择是直接尝试使用 C:\WINDOWS\System32,如果不存在,则尝试使用 C:\WinNT\System32,但感觉就像这样 hack那样做。

.Net Core 2.0 (and .Net Standard 2.0) will contain Environment.SystemDirectory,但当前的 1.x 版本没有。

虽然 属性 仍然作为 internal 存在,但如果您愿意依赖非 public 代码,一种解决方法是使用反射访问它:

using System;
using System.Reflection;
using static System.Reflection.BindingFlags;

…

var systemDirectory = typeof(Environment).GetProperty("SystemDirectory", NonPublic | Static)
    .GetValue(null, null);

在我的 Windows 10 机器上,.Net Core SDK 1.0 运行 在 .Net Core 1.1.1 上,这个 returns C:\WINDOWS\system32。 运行 Ubuntu 16.04 上的相同代码导致 NullReferenceException