How do I open a FolderBrowserDialog at the selected folder?

后端 未结 9 1893
深忆病人
深忆病人 2020-12-15 18:00

I have a FolderBrowserDialog, displayed with code shown below. However, it keeps opening with \'Computer\', i.e. the root of the folder tree, selected. How do I get it to

相关标签:
9条回答
  • 2020-12-15 18:23

    To select existing path (no special f...ng folders) you must write own treeview based form.

    0 讨论(0)
  • 2020-12-15 18:25

    Set rootfolder to

    Environment.SpecialFolder.Desktop
    

    and it should work as you want.

    It is the only way to actually set the initial selected folder. You'd think using

    Environment.SpecialFolder.MyComputer
    

    would work, but it doesn't.

    0 讨论(0)
  • 2020-12-15 18:29

    My solution, here

    I wrote this solution based on this solution by ParkerJay86. The solution worked on Windows 8 with several paths tested. Consider that your specified rootFolder should start with DriveLetter:\ like "C:\ProgramData"

            private void browseFolder_Click(object sender, EventArgs e)
            {
                String selectedPath;
                if (ShowFBD("C:\\", "Please Select a folder", out selectedPath))
                {
                    MessageBox.Show(selectedPath);
                }
            }
    
            public bool ShowFBD(String rootFolder, String title, out String selectedPath)
            {
                var shellType = Type.GetTypeFromProgID("Shell.Application");
                var shell = Activator.CreateInstance(shellType);
                var result = shellType.InvokeMember("BrowseForFolder", BindingFlags.InvokeMethod, null, shell, new object[] { 0, title, 0, rootFolder });
                if (result == null)
                {
                    selectedPath = "";
                    return false;
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    while (result != null)
                    {
                        var folderName = result.GetType().InvokeMember("Title", BindingFlags.GetProperty, null, result, null).ToString();
                        sb.Insert(0, String.Format("{0}\\", folderName));
                        result = result.GetType().InvokeMember("ParentFolder", BindingFlags.GetProperty, null, result, null);
                    }
                    selectedPath = sb.ToString();
    
                    selectedPath = Regex.Replace(selectedPath, @"Desktop\\Computer\\.*\(\w:\)\\", rootFolder.Substring(0, 3));
                    return true;
                }
            }
    
    0 讨论(0)
提交回复
热议问题