Returning errorlevels from C# applications

Something came up today which turned out to be a bit of a blast from the past. If you want to check the return value of a C# console application (for use in an old school batch file for example) you can’t rely on the return value of main (as you would in C for example), but have to set the value of System.Environment.ExitCode instead. The advantage to this over a single return statement is this call sets the exit code and won’t actually exit your program at that point, see below.

static void Main(string[] args)
{
	// program code...
	// now set the return value to 1
	System.Environment.ExitCode = 1
}

This example returns 1, which can then be picked up by some good ol’ fashioned batch command-goodness. I’m already reminiscing back to my 1000+ line BBS mailer batch file back in 1995!

Also came across this which provides guidance on the special meanings of some exit codes.

Tags: , , ,

  1. #1 by c on February 4th, 2009 - 6:19 pm

    May I just advise against using C# console applications should you wish to do some file i/o from a non-local location (a server hosted code repository, for instance); as you run into the .NET trust-wall-of-death, as your application will not be trusted to edit these files, and in order to gain this trust you must jump through the signing-hoops-from-hell, where you will never get the approach documented on MSDN to work, and will therefore fall back to a extremely dirty technique of hashing your assembly and forcing it into the list of trusted intranet located applications every time you build it, making your policy list some unsightly list of hexadecimal chuff that no human can read and decipher. I would recommend perl for this type of task, as merely falling onto your keyboard whilst napping at your desk should generate a more useable output.

    RE Q

SetPageWidth