继续打开 OpenFileDialog 直到选择有效文件 [英] Keep opening OpenFileDialog until selecting valid file

查看:33
本文介绍了继续打开 OpenFileDialog 直到选择有效文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有打开 OpenFileDialog 的代码,我正在检查文件的大小以确保它不超过特定限制.但是,如果用户选择了一个大文件,我需要警告他并引导他返回对话框选择其他文件或单击取消.

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.

这是我试过的:

        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;
                }
        }

我还尝试了以下代码,但每次调用 ShowDialog 时它都会打开对话框.因此,如果用户选择的文件大小为限制的 3 倍,则该对话框将出现 3 次.

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");
        }

推荐答案

您已经完成了一半,FileOk 事件正是您想要使用的.您缺少的是将 e.Cancel 属性设置为 true.这使对话框保持打开状态并避免您必须一遍又一遍地显示它.像这样:

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");
        }

这篇关于继续打开 OpenFileDialog 直到选择有效文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆