GrandOpener
GrandOpener

Reputation: 2123

Get the Windows system directory from a .NET Standard library

Seems like a simple question, but Google doesn't seem to have an answer for me.

In .NET Framework, we can use Environment.SystemDirectory to get the system directory (which will look something like C:\WINDOWS\System32), but that property does not exist in the current versions of .NET Standard or .NET Core. Is there a way to get that folder in a .NET Standard (or failing that, .NET Core) library?

For my purposes it is not required that the call return something useful on non-Windows platforms (and what would it return anyway? /lib? /usr/lib? etc.), although I guess it would be cool if it did.

Right now it seems like my best option is try to use C:\WINDOWS\System32 directly, and if that doesn't exist, then try to use C:\WinNT\System32, but it feels like such a hack to do it that way.

Upvotes: 4

Views: 2298

Answers (1)

svick
svick

Reputation: 244958

.Net Core 2.0 (and .Net Standard 2.0) will contain Environment.SystemDirectory, but the current 1.x versions don't.

Though the property still exists as internal, so one workaround would be to access it using reflection, if you're willing to rely on non-public code:

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

…

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

On my Windows 10 machine with .Net Core SDK 1.0 running on .Net Core 1.1.1, this returns C:\WINDOWS\system32. Running the same code on Ubuntu 16.04 results in NullReferenceException.

Upvotes: 6

Related Questions