3

I have a .NET service.

I have a .NET console application.

I want something along the lines of the service calling Process.Start("consoleapp.exe") and getting some information returned back from the app, ideally just returning a number.

How do I do this?

Edit:

I figure it must be: Process.Start("myapp.exe").ExitCode - but how do I set the exit code in the console app?

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
joshcomley
  • 28,099
  • 24
  • 107
  • 147

5 Answers5

12
Process p = Process.Start("app.exe");
p.WaitForExit();
int number = p.ExitCode;

And in app.exe you set Enviroment.ExitCode...

Jesper Palm
  • 7,170
  • 31
  • 36
3

you can make use of an Exit Code by changing your Main method from

public void Main(string[] args){return;}

to

public int Main(string[] args){return 0;}

Not an elegant solution, but it works.

Agent_9191
  • 7,216
  • 5
  • 33
  • 57
  • It is to a point. I guess it's because I'm not a huge fan of relying on arbitrary numbers of an exit code to mean something of use. Then again I rely on HTTP status codes all the time... – Agent_9191 Oct 19 '09 at 16:23
1

An arbitrary number can be returned via standard ExitCode mechanism. You'd just have to Start() a process, then WaitForExit(), and then get the value of ExitCode.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
1

You can use the exit code, which can be returned from the Main function or set via Environment.ExitCode.

Another option would be to have your ConsoleApp write to the standard output stream, and redirect the output to your main application.

The advantage of the second option is that you could return more data than a single integer, if later you find this necessary. The disadvantage is that it's a bit more work to setup.

This CodeProject article walks through redirecting the standard output streams of a spawned process.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

The console app can set its exit code.

The console app can set its exit code by either:

  1. Call System.Environment.Exit(exitcode), or
  2. Let the main function return an int.

The ExitCode property (of the System.Diagnostics.Process class) lets the service process examine the console app's exit code.

codeape
  • 97,830
  • 24
  • 159
  • 188