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

如何在C#编写的.NET工具中获取PowerShell的当前工作目录(pwd值)

获取dotnet tool run调用时的PowerShell当前工作目录

嘿,我知道你花了好几个小时找解决方案还没头绪——其实完全不用去调用PowerShell来获取pwd的值,.NET框架本身就提供了直接获取这个路径的方法,而且非常简单!

当你通过dotnet tool run myTool命令在PowerShell中调用你的.NET工具时,工具进程会继承调用它的PowerShell进程的当前工作目录。这意味着你根本不需要额外启动PowerShell会话去查询,直接用.NET内置的API就能拿到你要的路径。

修改你的代码如下:

class Program {
    static void Main(string[] args) {
        var pwd = GetCurrentWorkingDirectory();
        Console.WriteLine($"当前工作目录:{pwd}");
    }

    static string GetCurrentWorkingDirectory() {
        // 直接获取继承自PowerShell的当前工作目录
        return Environment.CurrentDirectory;
    }
}

为什么这个方法有效?

  • 当你在PowerShell的C:\Users\Samuel\AxisRepos>目录下执行dotnet tool run myTool时,.NET工具进程的工作目录会被自动设置为这个路径,Environment.CurrentDirectory会直接返回它。
  • 这个方法比调用PowerShell进程高效得多,也避免了零散代码整合的麻烦。

特殊情况说明

如果你的工具在启动时被显式修改了工作目录(比如通过某些配置或代码),那Environment.CurrentDirectory会返回修改后的路径。但默认情况下,dotnet tool run不会改变工具的工作目录,所以这个方法完全适用你的场景。

内容的提问来源于stack exchange,提问作者SamJ26

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:27:38