Naturally, a lot of my search engine traffic comes here from searching for terms like “system root in <insert 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 system’s environment variables and may be different from the System.Environment.SystemDirectory (docs) property.
1 2 3 4 |
//Get the %systemroot% value from the system's environment variables (e.g. 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.
1 2 |
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++.
1 |
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. 🙂
Wava Vittorio says:
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.
mark short says:
Thanks for this page! Although… %SystemRoot% is its own environment variable and isn’t really from “PATH” per se, which is another environment variable altogether. The “C:\Windows” in PATH and that in %SystemRoot% can possibly (but not likely) be different! You can see all those environment variable by pulling up a Command Prompt and entering the command: set
Richard Marskell says:
Nice catch, Mark. I’ve update the post to clarify. Cheers! 🙂
Hervé Mutombo Matanda says:
Good job on this one!