【问题标题】:Calling cmd.exe using Process in C# hanging在 C# 挂起中使用 Process 调用 cmd.exe
【发布时间】:2016-11-23 00:13:36
【问题描述】:

我正在尝试从 cmd.exe 中获取标准(测试“DIR”命令),并将其放入文本框中。但是,每当我启动该过程时,程序就会挂起(没有按下按钮)。

private void cmd_test()
{
    Process pr = new Process()
    {
        StartInfo = {
            FileName = "cmd.exe",
            UseShellExecute = true,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            RedirectStandardError = true,
        }
    };

    pr.Start();
    pr.StandardInput.WriteLine("DIR");
    TextBox1.Text = pr.StandardOutput.ReadToEnd();
}

我还尝试在 StartInfo 块中使用 Arguments = "DIR" 而不是 WriteLine。

如何正确地向 cmd.exe 发送命令而不使其挂起?

【问题讨论】:

    标签: c# cmd process command redirectstandardoutput


    【解决方案1】:

    给你:

      using (var p = new Process())
      {
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/C dir";
        p.Start();
        var output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        richTextBox1.Text = output;
      }
    

    【讨论】:

    • 工作,谢谢!你知道为什么它会挂在我的版本上吗?
    • UseShellExecute 也必须设置为 false 才能重定向输出流。更多信息在这里msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多