How to use a messagebox when an invalid directory is used with openfiledialog

75 Views Asked by At

I'm trying to create a VERY VERY simple file browser just to keep my novice c# in practice and a project to expand upon later, but I can't seem to execute code when an invalid directory is entered. With my current code, it redirects to Documents. When I press cancel, it goes back to Documents. If I cancel again, it displays the error I specified.

My current code is

private void button1_Click(object sender, EventArgs e)
{
    string dir = textBox1.Text;
    openFileDialog1.InitialDirectory = dir;
    DialogResult result = openFileDialog1.ShowDialog();
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    { 

    }
    else
    { 
        MessageBox.Show("Please Choose a valid directory.");
    }
}

Any help with this would be appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

Each time you call ShowDialog(), it displays the OpenFileDialog box, and you're calling it twice.

The first time, you store the user's selection in result, but do nothing else with it. You can hit OK or Cancel to this one - it makes no difference. You'll always get to the following line, which prompts the user again.

DialogResult result = openFileDialog1.ShowDialog();

The second time, you actually test the result and take some action. Hopefully in a real app there'd be some further test for whether or not the directory is valid, other than just that the user pressed "Cancel".

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    ...

If you don't need result later on, I'd suggest just removing the first line.