简体   繁体   English

OpenFileDialog xml过滤器允许.htm快捷方式

[英]OpenFileDialog xml Filter allowing .htm shortcuts

I've filedialog in winforms. 我在winforms中提交了文件。 It is set to read only .xml files. 它设置为只读.xml文件。

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

but when I run it is allowing to upload .htm file shortcut. 但是当我运行它时允许上传.htm文件快捷方式。 whereas it should not show .htm file at all. 而它根本不应该显示.htm文件。

You're doing it correctly. 你正确地做到了。 Using the Filter property allows you to limit the files displayed in the open dialog to only the specified type(s). 使用Filter属性可以将打开的对话框中显示的文件限制为仅指定的类型。 In this case, the only files the user will see in the dialog are those with the .xml extension. 在这种情况下,用户将在对话框中看到的唯一文件是扩展名为.xml

But, if they know what they're doing, it's trivial for the user to bypass the filter and select other types of files. 但是,如果他们知道他们正在做什么,那么用户绕过过滤器并选择其他类型的文件是微不足道的。 For example, they can just type in the complete name (and path, if necessary), or they can type in a new filter (eg *.* ) and force the dialog to show them all such files. 例如,他们只需键入完整的名称(和路径,如果需要),或者他们可以键入新的过滤器(例如*.* )并强制对话框向他们显示所有这些文件。

Therefore, you still need logic to check and make sure that the selected file meets your requirements. 因此,您仍需要逻辑来检查并确保所选文件符合您的要求。 Use the System.IO.Path.GetExtension method to get the extension from the selected file path, and do an ordinal case-insensitive comparison to the expected path. 使用System.IO.Path.GetExtension方法从所选文件路径获取扩展,并对预期路径进行序号不区分大小写的比较。

Example: 例:

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.
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM