当我尝试在proc.StandardInput.WriteLine(“ Y”)中编写内容时,我的应用程序将挂起

时间:2018-10-11 13:28:30

标签: c# c#-4.0

我尝试从C#代码执行命令。但是当我使用proc.StandardInput.WriteLine(“ Y”)时,我的应用程序挂起了。

我的代码在下面。

string command =“执行后,我的命令显示了一些输出和所需的用户输入”;

        System.Diagnostics.ProcessStartInfo procStartInfo =
            new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

        // The following commands are needed to redirect the standard output.
        // This means that it will be redirected to the Process.StandardOutput StreamReader.
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.RedirectStandardInput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        // Now we create a process, assign its ProcessStartInfo and start it
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();


        string standard_output;
        while ((standard_output = proc.StandardOutput.ReadLine()) != null)
        {
            if (standard_output.Contains("Are you sure (Y/y or N/n ):"))
            {
                proc.StandardInput.WriteLine("Y");
                //do something
                break;
            }
        }

1 个答案:

答案 0 :(得分:0)

 while ((standard_output = proc.StandardOutput.ReadLine()) != null)
        {
            if (standard_output.Contains("Are you sure (Y/y or N/n ):"))
            {
                proc.StandardInput.WriteLine("Y");
               string myReturn= proc.StandardInput.ReadLine();
                break;
            }
        }