如何使用C#获取Windows根目录?替换当前系统盘符可行性咨询
如何用C#获取Windows系统根目录并替换硬编码盘符?
这个需求完全可以实现,下面给你两种实用的解决方案:
方法一:通过系统目录路径提取根盘符
利用Environment.SystemDirectory获取Windows系统目录的完整路径,再通过Path.GetPathRoot提取其根盘符路径,最后拼接目标目录:
using System.IO; using System; // 获取系统盘的根路径(如C:\、D:\) string systemDriveRoot = Path.GetPathRoot(Environment.SystemDirectory); // 拼接成Windows Temp目录的完整路径 DirectoryInfo di = new DirectoryInfo(Path.Combine(systemDriveRoot, @"windows\temp"));
方法二:读取系统环境变量
直接读取SystemDrive环境变量获取系统盘符,再拼接根路径和目标目录:
using System.IO; using System; // 获取系统盘符(如C:) string systemDrive = Environment.GetEnvironmentVariable("SystemDrive"); // 拼接成完整的Temp路径 string tempPath = Path.Combine(systemDrive, @"\windows\temp"); DirectoryInfo di = new DirectoryInfo(tempPath);
两种方法都能自动适配系统所在的盘符,不用硬编码c:\,确保在不同系统安装路径下都能正常工作。
内容的提问来源于stack exchange,提问作者KrakenZ
相关产品推荐
相关产品推荐

