Wednesday, 6 January 2010

How to get the return value from an invoked application.

On the Windows operating system, an application’s return value is stored within a system environment variable named %ERRORLEVEL%. If you were to create an application that programmatically launches another executable, you can obtain the value of %ERRORLEVEL% using the static System.Diagnostics.Process.ExitCode property.


For example, the following program would return a value of "-1" when invoked:-

static int Main(string[] args)
{
// Display a message and wait for Enter key to be pressed.
Console.WriteLine("***** My First C# App *****");
Console.WriteLine("Hello World! ");
Console.WriteLine();
Console.ReadLine() ;
// Return an arbitrary error code.
return -1;
}



This program could then be called, and the return value evaluated, by using this following batch file for example:-

@echo off
rem A batch file for SimpleCSharpApp. exe
rem which captures the app' s return value.
SimpleCSharpApp
@if "%ERRORLEVEL%" == "0" goto success
: fail
echo This application has failed!
echo return value = %ERRORLEVEL%
goto end
: success
echo This application has succeeded!
echo return value = %ERRORLEVEL%
goto end
: end
echo All Done.