是否可以将非特殊文件夹用作FolderBrowserDialog的根文件夹?

时间:2012-10-18 03:09:38

标签: c# .net wpf winforms folderbrowserdialog

FolderBrowserDialog.RootFolder Property仅限于Environment.SpecialFolder枚举器中定义的特殊文件夹。但是在我的应用程序中,我们需要显示此对话框,但根路径需要是可配置的,并且通常是自定义文件夹,与枚举器中的任何特殊文件夹无关。

如何显示将根分配给自定义文件夹的文件夹浏览器?也许使用RootFolder属性是不可能的,但可以通过其他方式获得相同的效果(即用户无法在根文件夹之外查看或选择)。在this answer中,有人暗示可能使用反射操作,但没有更新。不知道这是否可以在.NET中使用?

1 个答案:

答案 0 :(得分:2)

我是根据ParkerJay86的this solution编写的。该解决方案适用于Windows 8,并测试了多个路径。请注意,您指定的rootFolder应以DriveLetter:\开头,例如“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;
    }
}