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");
}
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With