【问题标题】:C# Process Standard InputC# 处理标准输入
【发布时间】:2013-10-23 20:50:39
【问题描述】:

我目前正在尝试通过命令行断开与网络文件夹的连接,并使用以下代码:

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

有时,我收到消息“可以继续断开连接并强制关闭它们吗?(Y/N) [N]”,我想回复“Y”,但我似乎对此有疑问在职的。

有人知道为什么我的代码没有在标准输入中输入“Y”吗?

【问题讨论】:

  • 您正在重定向标准错误和输出,但实际上并未从中读取任何内容。如果您不想看到结果,请不要重定向它。还要注意读取标准输出和错误时常见的死锁陷阱;如果您不确保缓冲区被清空,缓冲区可能会被填满并永远坐在那里等待。
  • @MichaC 他将数据导向流程,而不是来自流程。
  • 试试 Console.WriteLine
  • @Matt 我认为您需要阅读问题的标题。

标签: c# stdin


【解决方案1】:

使用下方 代码 获取消息“可以继续断开连接并强制关闭它们吗?(Y/N)[N]”,回复哪个“是”

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/O 重定向,如此处所示的 console 应用程序想要在不打开新窗口的情况下调用另一个 Windows 可执行文件 - 它只会导致问题。对我有用的只是设置 UseShellExecute=false - 没有别的,见here
猜你喜欢
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多