Motivated Motivated - 28 days ago 7
C# Question

ExitCode not returned on CMD

I am currently working on a WPF Application which is providing

ExitCode
s to be found in the
Windows Eventlog
.

In some cases I need to cancel execution immediatly.
Therefore I use
Environment.Exit(someInteger)
.
There also is the need to start it via batch and check if the
ErrorLevel is NOT 0
.




Output via VisualStudio OutputConsole:

The program '[6908] MyApp.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[6908] MyApp.vshost.exe' has exited with code 3 (0x3).


CMD Output:

cd MyVisualStudioDebugDir
MyApp.exe
echo %errorlevel%
=> returns 0





Why am I getting 0 here when I call
Environment.Exit(3)
?

Answer

I'm not 100% sure but it could be related to how you might be invoking the EXE in your script. To mimic your situation, I created a simple WPF application that immediately exits via Environment.Exit(3); and then a simple test.cmd script:

@echo off

start /wait TestApp.exe
echo %ERRORLEVEL%

What was echoed was in fact 3.

Update: I noticed that the ERRORLEVEL is not properly set if start is used without the /wait option. I believe this is due to the fact that start will not wait for the application to exit before continuing. Therefore you can use start /wait TestApp.exe or simply call TestApp.exe. I have updated the example above.