简体   繁体   中英

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. 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.

How do I properly send a command to cmd.exe, without it hanging?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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