(Print this page)

Strange issue (bug) in the FolderBrowserDialog component (and a workaround)
Published date: Monday, April 11, 2016
On: Moer and Éric Moreau's web site

I found an issue in the FolderBrowserDialog component last week. This component is provided by Windows itself. From what I have read, Windows 7 and 10 have this issue but Windows and /8.1 are ok!.

The bug occurs when you show a FolderBrowserDialog and click the "Make New Folder" button at the bottom of the dialog. From there, type a name for the newly created folder BUT DO NOT PRESS THE ENTER KEY and click the OK button. The value returned in the SelectedPath property is showing "New Folder" instead of the name you just typed.

I have done extensive research and found a workaround. Not the ideal solution but at least, it returns the correct path!

private void button1_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dialog = new FolderBrowserDialog
    {
        ShowNewFolderButton = true
    };
    dialog.ShowDialog();
    string strSelectedPath = dialog.SelectedPath;

    //Check if the folder exist - if not most likely the bug described above
    if (!Directory.Exists(strSelectedPath)) 
    {
        //Set back to the folder where the new folder was created
        string strPathStart = CaseInsenstiveReplace(strSelectedPath, "New Folder", "");
        strSelectedPath = "";

        if (Directory.Exists(strPathStart))
        {
            try
            {
                DirectoryInfo diLatestFolder = null;
                foreach (DirectoryInfo di in new DirectoryInfo(strPathStart).GetDirectories())
                {
                    try
                    {
                        if ((diLatestFolder == null) || (di.CreationTime > diLatestFolder.CreationTime))
                            diLatestFolder = di;
                    }
                    catch 
                    {
                        //In case we don't have permission to another folder in the same level
                    }                            
                }
                if (diLatestFolder != null)
                    strSelectedPath = diLatestFolder.FullName;
            }
            catch 
            {
                //ignore
            }
        }
    }

    MessageBox.Show("SelectedPath = " + strSelectedPath + Environment.NewLine + 
                    "Original value = " + dialog.SelectedPath);
}

public static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue)
{
    Regex regEx = new Regex(oldValue, RegexOptions.IgnoreCase);
    return regEx.Replace(originalString, newValue);
}

If you want to see the original VB.Net code, check for the comment of Scott PRD of Oct. 6 2015 from http://www.pcreview.co.uk/threads/bug-in-folderbrowserdialog.2301005/


(Print this page)