FolderBrowserDialog and "." on my way

I ran into a problem using the fb.SelectedPath function in FolderBrowserDialog. Everything is fine as long as the absolute path does not contain any "." .

For instance:

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 "." , it moves the user to this folder. Let them say that the path is: "C: \ Prog" But if it returns the path using "." in it, for example, "C: \ Prog.Test", this will not work. It opens a dialog box, does not return any errors, but stucks to the "root" file of the file (if specified, otherwise it is "Desktop").

Any ideas how to solve this problem? Because it is quite annoying.

Thanks for the help.

UPDATE: Solved by the P key in this post: click me

+4
source share
1 answer

Path.GetDirectoryName does not know if it provided you with a folder with a point in it or a file with the extension (for example, a .txt file - a text file or a folder?).

If you know this directory, a workaround might be to do something like this.

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

This ensures that GetDirectoryName knows that it is looking at the directory and not at the file because of the tail \ .

Updated comment based response

This problem seems specific to FolderBrowserDialog (the above information should work in other cases). I was able to reproduce your problem, and I managed to find a relatively hacky solution, but it looks like this is a bug with FolderBrowserDialog , so that should be enough.

If you set the RootFolder property RootFolder value that contains the path you entered, it works. For example, if you set RootFolder to SpecialFolders.MyDocuments , and your input is C:\...\My Documents\test.dot.folder , it should work. Thus, the workaround is done using the SpecialFolders enumeration 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(); } 
+7
source

Source: https://habr.com/ru/post/1487500/


All Articles