C# Process Standard Input

雨燕双飞 提交于 2019-12-31 04:18:26

问题


I am currently trying to disconnect from a network folder through the command line and am using the following code:

System.Diagnostics.Process process2 = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C NET USE F: /delete";
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
process2.StartInfo = startInfo;
process2.Start();

StreamWriter sw = process2.StandardInput;
sw.WriteLine("Y");
sw.Close();

process2.WaitForExit();
process2.Close();

Occasionally, I get the message "Is it ok to continue disconnecting and force them closed? (Y/N) [N]", to which I want to reply "Y", but I seem to be having issues with that working.

Does anyone know why my code is not inputting "Y" to standard input?


回答1:


Use below code to get the message "Is it ok to continue disconnecting and force them closed? (Y/N) [N]", to which reply "Y"

static void Main(string[] args)
{
    System.Diagnostics.Process process2 = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = "/C NET USE F: /delete";
    startInfo.RedirectStandardError = true;
    startInfo.RedirectStandardInput = true;
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;
    process2.StartInfo = startInfo;
    process2.Start();

    Read(process2.StandardOutput);
    Read(process2.StandardError);

    while (true)
        process2.StandardInput.WriteLine("Y");

}

private static void Read(StreamReader reader)
{
    new Thread(() =>
    {
        while (true)
        {
            int current;
            while ((current = reader.Read()) >= 0)
                Console.Write((char)current);
        }
    }).Start();
}

I think this may help you..



来源:https://stackoverflow.com/questions/19552012/c-sharp-process-standard-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!