gpt4 book ai didi

c# - FolderBrowserDialog 和路径名中的 "."

转载 作者:太空狗 更新时间:2023-10-30 00:42:08 24 4
gpt4 key购买 nike

我在使用 FolderBrowserDialog 的 fb.SelectedPath 函数时遇到问题。一切都很好,只要绝对路径不包含任何“.”。

例如:

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

如果 System.Reflection.Assembly.GetExecutingAssembly().Location 不包含任何“.”,它会将用户导航到该文件夹​​。假设路径是这样的:“C:\Prog”但是如果它返回一个带有“.”的路径。在其中,如“C:\Prog.Test”,它将不起作用。它打开对话框,不返回任何错误,但停留在文件浏览器的“根目录”(如果指定,否则为“桌面”)。

任何想法如何解决这个问题?因为这很烦人。

感谢您的帮助。

更新: 由 keyboardP 在这篇文章中解决:click me

最佳答案

Path.GetDirectoryName 不知道您是否提供了带点的文件夹或带扩展名的文件(例如 file.txt 是文本文件还是文件夹? ).

如果您知道它是一个目录,解决方法可能是执行类似的操作。

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

这确保 GetDirectoryName 知道它正在查看目录而不是文件,因为尾随 \

根据评论更新答案

这个问题似乎是 FolderBrowserDialog 特有的(以上信息在其他情况下应该有效)。我能够重现您的问题,并且设法找到了一个相对复杂的解决方法,但它似乎是 FolderBrowserDialog 的错误,所以这应该足够了。

如果您将 RootFolder 属性设置为包含您正在输入的路径的属性,它就可以工作。例如,如果您将 RootFolder 设置为 SpecialFolders.MyDocuments 并且您的输入是 C:\...\My Documents\test.dot.folder,它应该工作。因此,解决方法遍历 SpecialFolders 枚举并设置第一个匹配项。

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

关于c# - FolderBrowserDialog 和路径名中的 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com