Reputation: 220
I have a program wherein I will check if a file exists. If it does, the form will load. But if not, a messagebox will appear to inform the user, and then the application needs to close without showing the form.
How do I do this properly? I tried using this code on the constructor:
Environment.Exit(-1);
It does what I want, but from what I've read it's not a good way to do it. Is this correct? Or shall I just go with using the above code.
Upvotes: 5
Views: 1492
Reputation: 216273
You don't need to call anything if you put your check before the application run of the main form
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Check for file
if(!File.Exists("your file to check"))
{
MessageBox.Show(.....)
}
else
{
Application.Run(new frmMain());
}
}
Upvotes: 9
Reputation: 1371
Try this: somewhat simpler (I think, I have understood you correctly)
if (File.Exists("somefile.txt"))
{
//do your operation
}
else
{
this.Close();
}
Upvotes: 0
Reputation: 1859
Try using this:
yourForm.close();
Or just don't call the form until you are sure that the file doesn't exist.
If you have other processes running you can call a method to close them all rather than have it with out cluttering up your main code.
Upvotes: 0