You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:55:29