简体   繁体   English

在C#挂起中使用Process调用cmd.exe

[英]Calling cmd.exe using Process in C# hanging

I am trying to get the standard out from cmd.exe (testing "DIR" command), and put it into a text box. 我正在尝试从cmd.exe(测试“ DIR”命令)中获取标准,并将其放入文本框中。 However, whenever I start the process the program hangs (no button presses). 但是,无论何时启动该程序,程序都会挂起(不按任何按钮)。

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();
}

I have also tried Arguments = "DIR" in the StartInfo block instead of WriteLine. 我还尝试了StartInfo块而不是WriteLine中的Arguments = "DIR"

How do I properly send a command to cmd.exe, without it hanging? 我如何正确地将命令发送到cmd.exe,而不将其挂起?

Here you go: 干得好:

  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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM