“StandardIn has not been redirected” error in .NET (C#)

余生长醉 提交于 2019-12-08 14:32:15

问题


I want to do a simple app using stdin. I want to create a list in one program and print it in another. I came up with the below.

I have no idea if app2 works however in app1 I get the exception "StandardIn has not been redirected." on writeline (inside the foreach statement). How do I do what I intend?

NOTE: I tried setting UseShellExecute to both true and false. Both cause this exception.

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

回答1:


You never Start() the new process.




回答2:


You must ensure ShellExecute is set to false in order for the redirection to work correctly.

You should also open a streamwriter on it, start the process, wait for the process to exit, and close the process.

Try replacing these lines:

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

with these:

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:


if you would like to see a simple example of how to write your process to a Stream use this code below as a Template feel free to change it to fit your needs..

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

//Change to add your work with your for loop




回答4:


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

You must set UseShellExecute to false if you want to set RedirectStandardInput to true. Otherwise, writing to the StandardInput stream throws an exception.

One might expect it to be false by default, that doesn't seem to be the case.



来源:https://stackoverflow.com/questions/8826884/standardin-has-not-been-redirected-error-in-net-c

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