I have code that opens OpenFileDialog, I check the file size to make sure that it does not exceed a certain limit. But if the user has selected a large file, I need to warn him and bring him back to the dialog box to select another file, or click the "Cancel" button.
Here is what I 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 a dialog every time ShowDialog is called. Thus, if the user selects a file whose size is 3 times the limit, a dialog box 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"); }
source share