Keep opening OpenFileDialog until selecting valid file

谁说我不能喝 提交于 2019-12-03 16:39:07

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

ev.Cancel = true; Check if following piece of code serves your purpose?

    public void SomeMethod()
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.FileOk += new CancelEventHandler(dialog_FileOk);
        dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
        dialog.ShowDialog();
    }

    void dialog_FileOk(object sender, CancelEventArgs e)
    {
        OpenFileDialog dialog = sender as  OpenFileDialog;
        var size = new FileInfo(dialog.FileName).Length;
        if (size > 250000)
        {
            MessageBox.Show("File size exceeded");
            e.Cancel = true;
          }

    }

Yes as far as your requirement is concern, this is OK but in general opening Dialog after showing a prompt for Size is not the best way. Instead a prompt should be displayed, best is to display the validation error on the size from the main window. And it should be User's duty to select the proper file again by opening the File Dialog again according to Usability principles of HCI.

Add a handler to FileDialog.FileOk and let verify the file size inside their.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!