ookii-dialogs / ookii-dialogs-wpf

Awesome dialogs for Windows Desktop applications built with Microsoft .NET (WPF)
BSD 3-Clause "New" or "Revised" License
1.14k stars 85 forks source link

VistaFolderBrowserDialog fails with exceptions when SelectedPath is set before ShowDialog() call #76

Open Miotis opened 2 years ago

Miotis commented 2 years ago

VistaFolderBrowserDialog.ShowDialog() can fail with deferent types of exceptions when we create a new instance VistaFolderBrowserDialog and set SelectedPath property.

I'm using this Dialog in a scenario when the user is able to manually input the path in text-block or call this dialog and select the correct path through it. I have some base validation on this text block, to ensure that the input string is a fully qualified DOS path string or correct network path. That's why I set SelectedPath with this user inputted string as a SelectedPath of the dialog and expect that it will try to find the existing folder or use an empty string in another case. My assumption, that this dialog should use exception safely check for SelectedPath string or use a null in another case.

Steps to reproduce

  1. I used MainWindow.xaml sample and change it a little to allow easily reproduce this case in Ookii.Dialogs.Wpf.Sample
    private void ShowFolderBrowserDialog()
        {
            var selectedPath = @"C:\..\";
            var dialog = new VistaFolderBrowserDialog(){SelectedPath = selectedPath };
            dialog.Description = "Please select a folder.";
            dialog.UseDescriptionForTitle = true; // This applies to the Vista style dialog only, not the old dialog.
    ...

This var selectedPath will produce Win32Exception during dialog.ShowDialog(this) calling. And it will be raised from public static Interop.IShellItem CreateItemFromParsingName(string path)

  1. Another case is PathToLongException that can be thrown if SelectedPath length exceeds the maximum allowed folder name or full pathname length. (just set selectedPath with really huge string). or ArgumentException (some incorrect chars in SelectedPath) This happens because of Path.GetDirectoryName(_selectedPath) in SetDialogProperties() method.

Path.GetDirectoryName() and Path.GetFileName() are not exception safe like Directory.Exists(). (see https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-6.0 and https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-6.0 for details). Looks like it's better to cover their usages with try/catch block and treat SelectedPath as an empty string in case of Win32Exception, PathToLongException, and ArgumentException to hold this case