How to find the systemroot (in C#, C++ and Java)

Naturally, a lot of my search engine traffic comes here from searching for terms like “system root in &ltinsert language here>” or “%systemroot%”. So, to live up to my domain, and you Googler’s expectations, I’ve decided to write a post about how to get the path to the system root in a few languages. If you know more, drop a comment and I’ll add it here.

C#

In C#, you can use the System.Environment.ExpandEnvironmentVariables (docs) method to get the system root. Note that this will get the %systemroot% from the PATH variable and may be different from the System.Environment.SystemDirectory (docs) property.

//Get the %systemroot% value from the PATH (i.e. C:\Windows)
Environment.ExpandEnvironmentVariables("%systemroot%");
//Get the system directory (i.e. C:\Windows\System32)
Environment.SystemDirectory;

C++

In C++, you can use the getenv() (docs) function from stdlib.h.

char * pSystemRoot;
pSystemRoot = getenv ("systemroot");

Java

In Java, we can use the System.getenv() method (docs) to get the systemroot environment variable. This is basically the same as C++.

System.getenv("SystemRoot");

That’s about it. If you know any more from other languages, leave a comment and I’ll add them to the list. :)


Be Sociable, Share!
Comments:
  • Wava Vittorio

    whoah this blog is fantastic i love reading your articles. Keep up the good work! You know, lots of people are looking around for this info, you can help them greatly.

    March 22, 2012 — 19:23
  • Leave a Reply

    %d bloggers like this: