'Close the application before the form loads
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.
Solution 1:[1]
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());
}
}
Solution 2:[2]
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.
Solution 3:[3]
Try this: somewhat simpler (I think, I have understood you correctly)
if (File.Exists("somefile.txt"))
{
//do your operation
}
else
{
this.Close();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | The_Cthulhu_Kid |
Solution 3 | Uthistran Selvaraj |