4

I'm facing a problem by using the fb.SelectedPath function of the FolderBrowserDialog. Everything is fine, as long as the absolute path does not contain any ".".

For example:

try
{
    if (arg == 1)
        fb_dialog.SelectedPath = Path.GetFullPath(tb_path.Text);
    else
        fb_dialog.SelectedPath = Path.GetFullPath(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
}
catch { fb_dialog.RootFolder = System.Environment.SpecialFolder.MyComputer; }

If System.Reflection.Assembly.GetExecutingAssembly().Location does not contain any ".", it navigates the user into that folder. Let's say the path is like that: "C:\Prog" But if it returns a path with a "." in it, like "C:\Prog.Test", it won't work. It opens the dialog, returns no errors but stucks at the "root" of the filebroser (if specified, otherwise its "Desktop").

Any Ideas how to solve that issue? Because it's quite annoying.

Thanks for help.

UPDATE: Solved by keyboardP in this post: click me

4

1 回答 1

7

Path.GetDirectoryName doesn't know whether or not you've provided a folder with a dot in it or a file with an extension (e.g. is file.txt a text file or a folder?).

If you know it's a directory, a workaround could be to do something like this.

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "\\")

This ensures that GetDirectoryName is aware it's looking at a directory and not at a file because of the trailing \.

Updated answer based on comments

This issue seems FolderBrowserDialog specific (the above info should work in other cases). I was able to reproduce your issue and I managed to find a relatively hacky workaround but it seems like it's a bug with the FolderBrowserDialog so this should suffice.

If you set the RootFolder property to one that contains the path you're inputting, it works. For example, if you set the RootFolder to SpecialFolders.MyDocuments and your input is C:\...\My Documents\test.dot.folder, it should work. Therefore, the workaround iterates through the SpecialFolders enum and sets the first match.

using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
   fbd.SelectedPath = Path.GetFullPath(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

   //find closest SpecialFolder that matches the input (can be expanded to not be case-sensitive)
   foreach (var sf in Enum.GetValues(typeof(Environment.SpecialFolder)))
   {
       string spath = Environment.GetFolderPath((Environment.SpecialFolder)sf);
       if (fbd.SelectedPath.Contains(spath))
       {
           fbd.RootFolder = (Environment.SpecialFolder)sf;
           break;
       }
   }

   fbd.ShowDialog();
}
于 2013-06-21T15:44:19.587 回答