My code reads text from a file. I need to add a method where if the file is not in the correct location, the program will exit.
try {
TextReader tr = new StreamReader("C:\\textfile.txt");
for (int i = 0; i < 4; i++)
{
ListLines[i] = tr.ReadLine();
}
}
catch (Exception e)
{
Console.WriteLine("File not found - the app will now exit");
}
Is it possible, and what commands should I use?
Three options spring to mind.
Firstly, you can just structure your code to return from the Main
method at that point. Unless you've got other (non-background) threads running, the application will then terminate.
Alternatively, you can just rethrow the exception, e.g. with throw
; - that will dump a stack trace to the console afterwards, which may or may not be what you want.
Finally, you can use Environment.Exit
which will terminate the process. For example:
using System;
class Test
{
public static void Main (string[] args)
{
Console.WriteLine("Before");
Environment.Exit(1);
Console.WriteLine("After");
}
}
Here, Before
will be printed, but After
won't be.
See more on this question at Stackoverflow