1

I used this code to execute multi cmd commands in C#.
First i created constructor to create process.

public CMD()
        {
            process = new Process();
            startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;
            startInfo.FileName = "cmd.exe";
            startInfo.Verb = "runas";
            process.StartInfo = startInfo;
            process.Start();
            process.EnableRaisingEvents = true;
            process.StandardInput.AutoFlush = true;
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.OutputDataReceived += Process_OutputDataReceived;
            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.Exited += Process_Exited;
        }

then i used this code to execute multi commands.

public void _cmd(string command)
        {
            using (StreamWriter sw = process.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine(command);
                }
            }
        }

for the first command is not any problem but when i send second one i got this error in sw.BaseStream.CanWrite line.

Object reference not set to an instance of an object.

when i debug code for the first time sw.BaseStream is OK but in second command it get null
what is problem here ?

abrpr
  • 11
  • 2

1 Answers1

2

I suspect it's because of your using statement. When the using block is exited, it will call Dispose in process.StandardInput().

Stevo
  • 1,424
  • 11
  • 20
  • yes that's right but when i removed `using` statement i don't get any output. it seems that it should be dispose or close to get outpout. is there any way ? – abrpr Jul 26 '18 at 15:29
  • Call `Flush()` on the stream maybe? – Stevo Jul 26 '18 at 15:30
  • Flush() was not helpful. – abrpr Aug 06 '18 at 07:06
  • Have a look a this: https://stackoverflow.com/questions/13778236/c-sharp-console-application-stdin-stdout-redirection. Here's the code I ended up using in the end: https://github.com/stevehjohn/Hub/blob/master/Ming/MingMongoPlugin/TabDocuments/MongoConsole.cs – Stevo Aug 06 '18 at 15:05