如何显示阻止 OpenFileDialog 类在 C# 中关闭的错误?

How can I display an error which prevents the OpenFileDialog class from closing in C#? [closed]
2021-11-25
  •  译文(汉语)
  •  原文(英语)

我正在创建一个基本的绘图程序,用户可以在其中通过单击类中的某个 .png 文件来打开项目.我正在使用 System.Windows.Forms.OpenFileDialog 类.如果用户尝试打开错误的文件,我如何才能使对话框显示错误而不关闭?例如:我希望用户单击文件"name.png"但用户单击名为"picture.png"的文件.现在会出现一个错误,要求用户找到"name.png"并且不关闭对话框.

这是我的代码:

        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "*.png Files|*.png|All files|*.*";
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            if (openFileDialog.FileName.EndsWith(".png"))
            {
                if(openFileDialog.FileName.Equals("name.png"))
                {
                    //name.png found
                }
                else
                {
                    // it was the wrong file!    
                }
            }
        }
解决过程1

而不是事后检查结果,将过滤器设置为Name file|name.png.

这样,用户只能选择您想要的文件,而无需进行额外的检查.

I am creating a basic drawing program in which the user can open projects by clicking on a certain .png file in the class. I am using the System.Windows.Forms.OpenFileDialog class. How can I make it so the Dialog shows an error, without closing, if the user tries to open the wrong file? For example: I want the user to click on the file "name.png" but the user clicks on a file named "picture.png". Now an error shows up asking the user to find the "name.png" and doesn't close the dialog.

Here is my code:

        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "*.png Files|*.png|All files|*.*";
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            if (openFileDialog.FileName.EndsWith(".png"))
            {
                if(openFileDialog.FileName.Equals("name.png"))
                {
                    //name.png found
                }
                else
                {
                    // it was the wrong file!    
                }
            }
        }
Solutions1

Instead of checking the results afterwards, set the filter to be Name file|name.png.

This way, the user is only able to select the file you desire, and there's no need for the additional checks.

转载于:https://stackoverflow.com/questions/15238041/how-can-i-display-an-error-which-prevents-the-openfiledialog-class-from-closing

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入