0

I want to launch a command line program from C# code, then when it finishes relaunch the process again.

The command line program downloads some files and kills the C# process, and I need to relaunch my C# program when the command line process is finished. I've tried the following:

Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.WorkingDirectory = path-to-the-cmd-program;
p.StartInfo.FileName = cmd-program-name;
p.StartInfo.Arguments = "--arg1 blah --arg2 blah & path-to-csharp-program\\c-sharp-program.exe"
p.Start();

But for some reason, when the command line process finishes (it finishes successfully), the rest of the arguments (which should call the C# program again) get ignored.

If I try to do the same from cmd, it works as expected: process 1 finishes, then C# program is launched.

I also tried trying to set the p.Exited event handler, but of course, C# process is killed so the event handler does not fire.

Thank you very much.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • The arguments all get passed to your program. The shell doesn't have them anymore. – Robert Harvey Sep 08 '20 at 12:45
  • It is a node program that I did not code, but a coworker of mine. However, it works just fine when launching it from cmd the exact same way as I'm doing it from C# code. – Carlos M. Hernández Sep 08 '20 at 12:46
  • Because you're launching it from the shell. I don't think Process.StartInfo works that way, even if `UseShellExecute=true;` – Robert Harvey Sep 08 '20 at 12:47
  • In C#, you can wait the end of the process and relaunch. – vernou Sep 08 '20 at 12:49
  • 1
    Or start "cmd" process and pass `cmd-program-name` in argument. – vernou Sep 08 '20 at 12:49
  • @RobertHarvey So all the arguments are passed to the program and not the shell? Could I do something like launching cmd with all the arguments and then I can use "&"? – Carlos M. Hernández Sep 08 '20 at 12:50
  • I cannot wait for the end of the Node process, since that one kills the C# process. If I wait, then the Node process fails because it cannot kill the C# process. @Vernou – Carlos M. Hernández Sep 08 '20 at 12:51
  • 1
    `Could I do something like launching cmd with all the arguments and then I can use "&"?` -- That might work. – Robert Harvey Sep 08 '20 at 12:53
  • @RobertHarvey Yeah that worked. Just a little thing: arguments passed to the cmd program should start with "/c". You might want to write an answer in order to get it accepted. Thank you! – Carlos M. Hernández Sep 08 '20 at 13:28
  • The `&` character is understood only by the command-line interpreter. It's not inherent to Windows. So you need to use a command-line interpreter to run your command, e.g. `cmd.exe`. See duplicate. – Peter Duniho Sep 08 '20 at 15:59

0 Answers0