&引用;StandardIn未被重定向”;.NET中的错误(C#)

&引用;StandardIn未被重定向”;.NET中的错误(C#),c#,.net,stdin,C#,.net,Stdin,我想用stdin做一个简单的应用程序。我想在一个程序中创建一个列表,然后在另一个程序中打印它。我想出了下面的答案 我不知道app2是否工作,但是在app1中,我在writeline(foreach语句内部)上收到异常“StandardIn未被重定向”。我该如何做我想做的事 注意:我尝试将UseShellExecute设置为true和false。两者都会导致此异常 //app1 { var p = new Process();

我想用stdin做一个简单的应用程序。我想在一个程序中创建一个列表,然后在另一个程序中打印它。我想出了下面的答案

我不知道app2是否工作,但是在app1中,我在writeline(foreach语句内部)上收到异常“StandardIn未被重定向”。我该如何做我想做的事

注意:我尝试将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);
    }

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

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

默认情况下,您可能会认为它为false,但事实并非如此。

您从未启动()新进程。

您必须确保ShellExecute设置为false,以便重定向正常工作

您还应该在其上打开streamwriter,启动流程,等待流程退出,然后关闭流程

尝试替换以下行:

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

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

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循环添加您的工作

您是否希望执行p=Process.Start(v);例如还设置p.UseShellExecute=false;是我干的。问题是忘记了开始