Close the application before loading the form.

I have a program in which I will check if a file exists. If this happens, the form will load. But if not, a message appears informing the user, and then the application should close without showing the form.

How do I do it right? I tried using this code in the constructor:

    Environment.Exit(-1);

He does what I want, but from what I read, this is not a good way to do this. It's right? Or I'll just use the code above.

+5
source share
3 answers

You do not need to name anything if you put your check before starting the main form application

    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());
        }
    }
+8
source

Try using this:

yourForm.close();

Or simply do not call the form until you are sure that the file does not exist.

, , , , .

0

Try the following: a little easier (I think I understood you correctly)

if (File.Exists("somefile.txt"))
{
   //do your operation
}
else
{
    this.Close();
}
0
source

All Articles