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 ?

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 ?
Call Flush() on the stream maybe?
Flush() was not helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.