Select folder dialog WPF

后端 未结 10 708
暗喜
暗喜 2020-11-28 19:32

I develop a WPF4 application and in my app I need to let the user select a folder where the application will store something (files, generated reports etc.).

My requ

10条回答
  •  旧时难觅i
    2020-11-28 19:58

    If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

    No using directive needed, you may simply copy-paste the code below !

    It should still be very user-friendly and most people will never notice.

    The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

    It is a big hack for sure, but maybe it will do the job just fine for your usage...

    In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

    // Create a "Save As" dialog for selecting a directory (HACK)
    var dialog = new Microsoft.Win32.SaveFileDialog();
    dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
    dialog.Title = "Select a Directory"; // instead of default "Save As"
    dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
    dialog.FileName = "select"; // Filename will then be "select.this.directory"
    if (dialog.ShowDialog() == true) {
        string path = dialog.FileName;
        // Remove fake filename from resulting path
        path = path.Replace("\\select.this.directory", "");
        path = path.Replace(".this.directory", "");
        // If user has changed the filename, create the new directory
        if (!System.IO.Directory.Exists(path)) {
            System.IO.Directory.CreateDirectory(path);
        }
        // Our final value is in path
        textbox.Text = path;
    }
    

    The only issues with this hack are :

    • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
    • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
    • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

    Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

提交回复
热议问题