3

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?

0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've gone with the Environment.Exit :)
3

You can use Environment.Exit(0); and Application.Exit

try { TextReader tr = new StreamReader("C:\\textfile.txt"); for (int i = 0; i < 4; i++) { ListLines[i] = tr.ReadLine(); } } catch (Exception e) { Environment.Exit(0) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.