Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

stdin

You never Start() the new process.


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

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


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.