Is it possible to use non-special folder as a FolderBrowserDialog's root folder?

[亡魂溺海] 提交于 2019-12-20 01:41:22

问题


FolderBrowserDialog.RootFolder Property is restricted to only special folder defined in the Environment.SpecialFolder enumerator. However in my applciation, we need to show this dialog, but the root path needs to be configurable, and is normally a custom folder, not related to any of the special folder in the enumerator.

How can I show a folder browser with the root assigned to a custom folder? Maybe it's not possible with RootFolder property, but is it possible to have the same effect by other means (i.e. user can't view or select outside the root folder). In this answer, somebody hinted that it might be possible using reflection manipulation, but there was no update. Any idea if this is possible in .NET?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/12946488/is-it-possible-to-use-non-special-folder-as-a-folderbrowserdialogs-root-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!