1

Possible Duplicate:
Capture console exit C#

When I run my console app and the user closes it by closing the console window, the exit code is 0. How to set specific error code in such cases?

Community
  • 1
  • 1
Louis Rhys
  • 34,517
  • 56
  • 153
  • 221
  • 5
    possible duplicate of [Capture console exit C#](http://stackoverflow.com/questions/474679/capture-console-exit-c-sharp), [“On Exit” for a Console Application](http://stackoverflow.com/questions/4646827/on-exit-for-a-console-application) – Cody Gray - on strike Feb 02 '12 at 05:29
  • What are you using to "abruptly close" your app? – M.Babcock Feb 02 '12 at 05:35

1 Answers1

3

One way is to set the ExitCode to whatever you want at anytime throughout the program and at the end of the program, set it to 0. In my example, if the user closes the console before the application completes, it reports ExitCode -1, otherwise it sets the ExitCode to 0:

    static void Main(string[] args)
    {
        Environment.ExitCode = -1;
        for (int i = 0; i < 20; i++)
        {
            Thread.Sleep(1000);
        }

        Environment.ExitCode = 0;
        Console.WriteLine("Done!");
    }
doogle
  • 3,376
  • 18
  • 23