Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep opening OpenFileDialog until selecting valid file

I have code that opens the OpenFileDialog, I'm checking the size of the file to make sure it doesn't exceed specific limit. But, if the user selected a big sized file I need to warn him and lead him back to the dialog to select a different file or click cancel.

This is what I've tried:

        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
        while (dialog.ShowDialog() != DialogResult.Cancel)
        {
                var size = new FileInfo(dialog.FileName).Length;
                if (size > 250000)
                {
                    MessageBox.Show("File size exceeded");
                    continue;
                }
        }

EDIT: I also tried the following code but it opens the dialog each time the ShowDialog is called. So, if the user selected a file 3x the size the limit, the dialog will appear 3 times.

  OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
        dialog.FileOk += delegate(object s, CancelEventArgs ev)
        {
            var size = new FileInfo(dialog.FileName).Length;
            if (size > 250000)
            {
                XtraMessageBox.Show("File size");
                dialog.ShowDialog();
            }
        };
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            XtraMessageBox.Show("File Selected");
        }
like image 989
Nour Avatar asked Jan 16 '23 09:01

Nour


1 Answers

You are half-way there, the FileOk event is what you want to use. What you are missing is setting the e.Cancel property to true. That keeps the dialog opened and avoids you having to display it over and over again. Like this:

        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
        dialog.FileOk += delegate(object s, CancelEventArgs ev) {
            var size = new FileInfo(dialog.FileName).Length;
            if (size > 250000) {
                MessageBox.Show("Sorry, file is too large");
                ev.Cancel = true;             // <== here
            }
        };
        if (dialog.ShowDialog() == DialogResult.OK) {
            MessageBox.Show(dialog.FileName + " selected");
        }
like image 121
Hans Passant Avatar answered Jan 21 '23 20:01

Hans Passant