Search code examples
c#.netdirectory

How to get root directory of windows using C#?


DirectoryInfo di = new DirectoryInfo(@"c:\windows\temp");

Here I want to replace c:\ with the current drive on which the user is operating windows. Is it possible to do that?


Solution

  • Both Environment.GetEnvironmentVariable("SystemRoot") and Environment.GetEnvironmentVariable("windir") should give you the path in form of "driveLetter:\\Windows"

    So you can do:

    DirectoryInfo di = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
    

    For the difference between "SystemRoot" and "windir" see: https://superuser.com/questions/638321/what-is-difference-between-windir-and-systemroot