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

C#中Process.Start()重定向标准输出时触发“访问被拒绝”错误

问题描述

我尝试通过以下代码在.NET应用中创建并启动进程:

var startInfo = new ProcessStartInfo
{
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy Bypass -File {ps1FilePath}",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    CreateNoWindow = true
};
using (Process process = new Process { StartInfo = startInfo })
{   
    process.Start();
   // Some code...
}

仅当设置RedirectStandardOutput = true时,process.Start()会失败并抛出“访问被拒绝”异常;移除该设置后,进程可正常启动并完成。我调试后发现问题与输出重定向的管道创建有关,但因是Windows代码无法进一步调试。

请问是否需要进行额外配置以允许输出重定向?

我尝试运行cmd.exe dir这类简单命令时,只要尝试输出重定向就会出现相同错误。

解决方案

1. 检查运行权限

启用输出重定向时,跨进程管道的创建需要足够权限。如果应用在低权限上下文(如标准用户、UAC限制)运行,可能被Windows权限机制阻止:

  • 右键以管理员身份运行.NET应用,验证错误是否消失。
  • 若为服务/后台程序,确保运行账户(如LocalSystem或管理员账户)拥有对应权限。

2. 确认工作目录与UseShellExecute设置

UseShellExecute = false是重定向输出的必要条件,需确保未被其他代码修改。同时,显式设置有读写权限的工作目录:

var startInfo = new ProcessStartInfo
{
    // 其他原有配置
    WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory
};

3. 检查本地安全策略

Windows本地安全策略可能限制管道创建:

  • 打开secpol.msc,导航到本地策略 > 用户权限分配,检查:
    • 创建全局对象:确保当前用户/账户组已添加。
    • 替换进程级令牌:若应用需模拟用户,确认权限已配置。

4. 排查安全软件干扰

杀毒软件或EDR工具可能拦截跨进程管道操作,临时禁用安全软件验证是否解决问题。若有效,将.NET应用、powershell.exe、cmd.exe添加到信任列表。

5. 同时重定向标准错误流

仅重定向StandardOutput可能引发权限问题,尝试同时重定向StandardError,并确保读取流避免进程挂起:

var startInfo = new ProcessStartInfo
{
    FileName = "powershell.exe",
    Arguments = $"-NoProfile -ExecutionPolicy Bypass -File {ps1FilePath}",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
    WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory
};
using (Process process = new Process { StartInfo = startInfo })
{   
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    process.WaitForExit();
    // 处理输出或错误
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:32:19