.net 查找目录中的所有目录并仅返回名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17568166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find all directories in directory and return only name
提问by ad48
I want to find all directories in one directory in vb.net.
我想在 vb.net 的一个目录中找到所有目录。
I found one script:
我找到了一个脚本:
For Each Dir As String In Directory.GetDirectories(FolderName)
ComboBox3.Items.Add(Dir)
Next
It returns full name of path, but I want it to return only name of path.
它返回路径的全名,但我希望它只返回路径的名称。
回答by Adrian Wragg
The simplest way is to use System.IO.DirectoryInfo:
最简单的方法是使用System.IO.DirectoryInfo:
For Each Dir As String In System.IO.Directory.GetDirectories(FolderName)
Dim dirInfo As New System.IO.DirectoryInfo(Dir)
ComboBox3.Items.Add(dirInfo.Name)
Next
(Obviously, you could parse it manually and extract out the text following the final '\', but I believe that the above is more readable)
(显然,您可以手动解析它并提取出最后一个 '\' 后面的文本,但我相信上面的内容更具可读性)
回答by MarcinJuraszek
I think the easiest way would be using String.Replaceto remove FolderNamefrom the beginning of the directory full name.
我认为最简单的方法是使用从目录全名的开头String.Replace删除FolderName。
For Each Dir As String In System.IO.Directory.GetDirectories(FolderName)
ComboBox3.Items.Add(Dir.Replace(FolderName, String.Empty))
Next
回答by SysDragon
Use this to get only the directory name:
使用它来仅获取目录名称:
dirName = IO.Path.GetDirectoryName(fullPath)
回答by dbasnett
Give this a try
试试这个
For Each d As String In IO.Directory.GetDirectories(FolderName)
'IO.Path.GetFileName
'The characters after the last directory character in path.
ComboBox3.Items.Add(IO.Path.GetFileName(d))
Next
This takes advantage of the fact that you have a list of directories and what IO.Path.GetFileName actually does.
这利用了以下事实:您有一个目录列表以及 IO.Path.GetFileName 实际执行的操作。
回答by Mustafa
For Each Dir As String In Directory.GetDirectories(FolderName)
ComboBox3.Items.Add(IO.Path.GetFileName(Dir))
Next

