【问题标题】:"StandardIn has not been redirected" error in .NET (C#).NET (C#) 中的“StandardIn 尚未重定向”错误
【发布时间】:2012-02-08 06:11:56
【问题描述】:

我想用标准输入做一个简单的应用程序。我想在一个程序中创建一个列表并在另一个程序中打印它。我想出了以下内容。

我不知道 app2 是否可以工作,但在 app1 中出现异常“StandardIn 尚未重定向”。在 writeline 上(在 foreach 语句内)。我该怎么做?

注意:我尝试将 UseShellExecute 设置为 true 和 false。两者都会导致此异常。

        //app1
        {
            var p = new Process();
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.FileName = @"path\bin\Debug\print_out_test.exe";
            foreach(var v in lsStatic){
                p.StandardInput.WriteLine(v);
            }
            p.StandardInput.Close();
        }

    //app 2
    static void Main(string[] args)
    {
        var r = new StreamReader(Console.OpenStandardInput());
        var sz = r.ReadToEnd();
        Console.WriteLine(sz);
    }

【问题讨论】:

  • 你希望做 p = Process.Start(v);例如..??还设置 p.UseShellExecute = false;

标签: c# .net stdin


【解决方案1】:

你永远不会 Start() 新进程。

【讨论】:

    【解决方案2】:

    您必须确保将 ShellExecute 设置为 false 才能使重定向正常工作。

    您还应该在其上打开流写入器,启动进程,等待进程退出,然后关闭进程。

    尝试替换这些行:

            foreach(var v in lsStatic){
                p.StandardInput.WriteLine(v);
            }
            p.StandardInput.Close();
    

    这些:

    p.Start();
    using (StreamWriter sr= p.StandardInput)
    {
         foreach(var v in lsStatic){
             sr.WriteLine(v);
         }
         sr.Close();
    }
    // Wait for the write to be completed
    p.WaitForExit();
    p.Close();
    

    【讨论】:

      【解决方案3】:

      如果您想查看如何将流程写入 Stream 的简单示例,请使用下面的代码作为模板,随意更改它以满足您的需求。

      class MyTestProcess
      {
          static void Main()
          {
              Process p = new Process();
              p.StartInfo.UseShellExecute = false ;
              p.StartInfo.RedirectStandardInput = true;
              p.StartInfo.RedirectStandardOutput = true;
      
              p.StartInfo.FileName = @"path\bin\Debug\print_out_test.exe";
              p.StartInfo.CreateNoWindow = true;
              p.Start();
      
              System.IO.StreamWriter wr = p.StandardInput;
              System.IO.StreamReader rr = p.StandardOutput;
      
              wr.Write("BlaBlaBla" + "\n");
              Console.WriteLine(rr.ReadToEnd());
              wr.Flush();
          }
      }
      

      //更改为使用 for 循环添加您的工作

      【讨论】:

        【解决方案4】:

        来自http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx

        如果要将 RedirectStandardInput 设置为 true,则必须将 UseShellExecute 设置为 false。否则,写入 StandardInput 流会引发异常。

        人们可能会认为它默认为 false,但似乎并非如此。

        【讨论】:

        • 我确实这样做了。问题是忘记了 start()
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多