“StandardIn has not been redirected” error in .NET

2019-06-14 22:06发布

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

标签: c# .net stdin
4条回答
Lonely孤独者°
2楼-- · 2019-06-14 22:22

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楼-- · 2019-06-14 22:39

You never Start() the new process.

查看更多
该账号已被封号
4楼-- · 2019-06-14 22:40

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.

查看更多
够拽才男人
5楼-- · 2019-06-14 22:41

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

查看更多
登录 后发表回答