【问题标题】:OpenFileDialog xml Filter allowing .htm shortcutsOpenFileDialog xml过滤器允许.htm快捷方式
【发布时间】:2013-07-10 09:51:27
【问题描述】:

我已经在 winforms 中打开了文件对话框。 它设置为只读 .xml 文件。

ofd.DefaultExt="xml";
ofd.Filter="XML Files|*.xml";

但是当我运行它时,它允许上传 .htm 文件快捷方式。而它根本不应该显示 .htm 文件。

【问题讨论】:

    标签: c# winforms openfiledialog


    【解决方案1】:

    你做得对。使用Filter 属性可以将打开的对话框中显示的文件限制为仅指定的类型。在这种情况下,用户将在对话框中看到的唯一文件是带有 .xml 扩展名的文件。

    但是,如果他们知道自己在做什么,那么用户绕过过滤器并选择其他类型的文件是微不足道的。例如,他们可以只输入完整的名称(和路径,如有必要),或者他们可以输入新的过滤器(例如*.*)并强制对话框显示所有此类文件。

    因此,您仍然需要逻辑来检查并确保所选文件符合您的要求。使用System.IO.Path.GetExtension 方法从选定的文件路径中获取扩展名,并与预期路径进行不区分大小写的顺序比较。

    例子:

    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "XML Files (*.xml)|*.xml";
    ofd.FilterIndex = 0;
    ofd.DefaultExt = "xml";
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        if (!String.Equals(Path.GetExtension(ofd.FileName),
                           ".xml",
                           StringComparison.OrdinalIgnoreCase))
        {
            // Invalid file type selected; display an error.
            MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
                            "Invalid File Type",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
    
            // Optionally, force the user to select another file.
            // ...
        }
        else
        {
            // The selected file is good; do something with it.
            // ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      相关资源
      最近更新 更多