简体   繁体   中英

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?

In .net you ought to use Path.GetTempPath to get a temporary path:

https://learn.microsoft.com/en-us/do.net/api/system.io.path.gettemppath?view.net-7.0&tabs=windows

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

 DirectoryInfo di2 = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
            string path = Convert.ToString(di2);
            
            DirectoryInfo di = new DirectoryInfo( path + @"\temp");

I figured it out. Here is the corrected code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM