abrpr
abrpr

Reputation: 11

C# Error in Executing multiple command lines

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 ?

Upvotes: 1

Views: 68

Answers (1)

Stevo
Stevo

Reputation: 1434

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

Upvotes: 2

Related Questions