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.
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;
In C++, you can use the
getenv() (docs) function from stdlib.h.
char * pSystemRoot; pSystemRoot = getenv ("systemroot");
In Java, we can use the
System.getenv() method (docs) to get the systemroot environment variable. This is basically the same as C++.
That’s about it. If you know any more from other languages, leave a comment and I’ll add them to the list.