.NET中没有"StandardIn未被重定向"错误(C#)

21 .net c# stdin

我想用stdin做一个简单的应用程序.我想在一个程序中创建一个列表并在另一个程序中打印它.我想出了下面的内容.

我不知道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);
    }
Run Code Online (Sandbox Code Playgroud)

its*_*e86 31

你永远不会开始()新的过程.

  • 哦,哦,哇,是的,它修正了. (5认同)

com*_*ech 10

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

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

尝试替换这些行:

        foreach(var v in lsStatic){
            p.StandardInput.WriteLine(v);
        }
        p.StandardInput.Close();
Run Code Online (Sandbox Code Playgroud)

用这些:

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();
Run Code Online (Sandbox Code Playgroud)


Met*_*Man 8

如果您想看一个如何将您的流程编写到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();
    }
}
Run Code Online (Sandbox Code Playgroud)

//更改以使用for循环添加工作