0

enter code hereI want to send a command to cmd after the first command I sent will end. When I'm trying to call another command by BeginErrorReadLine() there is an error: "An async operation already started on the stream".

How can I connect the process again and send another command? (I want to send the second command by pressing another button).

First command with cmd process:

ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = "python.exe";
cmdStartInfo.Arguments = ConfigurationManager.AppSettings["ttk"] + commandline;
cmdStartInfo.CreateNoWindow = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

_cmd = new Process();
_cmd.StartInfo = cmdStartInfo;


if (_cmd.Start())
{
    _cmd.OutputDataReceived += new DataReceivedEventHandler(_cmd_OutputDataReceived);
    _cmd.ErrorDataReceived += new DataReceivedEventHandler(_cmd_ErrorDataReceived);
    _cmd.Exited += new EventHandler(_cmd_Exited);

    _cmd.BeginOutputReadLine();
    _cmd.BeginErrorReadLine();


}
else
{
    _cmd = null;
}
user2026
  • 61
  • 1
  • 11
  • btw System.Net can send ICMP pings ... – Alex K. Sep 23 '14 at 11:12
  • 1
    This is ugly. In your case there's no need for .NET, you could achieve everything with a simple batch script. – Rob Sep 23 '14 at 11:14
  • @Robert the ping is only an example. actually i'm using a python script ant i want to send to this script a command at the end of the first. Do you have a solution? – user2026 Sep 30 '14 at 12:49

1 Answers1

0

IIRC Process has an Exited event to achieve this. In your case, it would then be:

// non-blocking
_cmd.Exited += (sender, eventArgs) => { /* run after process exists */ };

or, if blocking is ok, you just go like this:

_cmd.Start();
_cmd.WaitForExit(); // Blocking (until _cmd exists)
Alex
  • 23,004
  • 4
  • 39
  • 73
  • How do I do this with in new button? – user2026 Sep 23 '14 at 12:36
  • But i don't know what to write in this handler. How can I refer to the script again, after it finished, and run a new command. (I dont want to close the process, just to connect it again). Thanks!! – user2026 Sep 29 '14 at 12:48
  • You mean something like this ? http://stackoverflow.com/questions/2851402/execute-multiple-command-lines-with-the-same-process-using-c-sharp – Alex Sep 29 '14 at 13:27
  • I need to call the second command with a click on button2. However my process is asynchronous. How can I refer again to this proccess by button click and send another command? – user2026 Sep 30 '14 at 13:23