Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenFileDialog xml Filter allowing .htm shortcuts

I've filedialog in winforms. It is set to read only .xml files.

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

but when I run it is allowing to upload .htm file shortcut. whereas it should not show .htm file at all.

like image 708
hungrycoder Avatar asked Dec 20 '22 03:12

hungrycoder


1 Answers

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). In this case, the only files the user will see in the dialog are those with the .xml extension.

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 (e.g. *.*) 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.

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.
        // ...
    }
}
like image 176
Cody Gray Avatar answered Jan 28 '23 21:01

Cody Gray