如何在不包含所述文件夹的父目录的情况下获取文件夹中的子目录?
How do I get the subdirectories in a folder without including the parent directory of said folder?
我知道 IO.Directory.GetDirectories("X:/mydata/backup/stuff", "*", IO.SearchOption.AllDirectories)
可用于获取所有目录,但我需要弄清楚如何不将父部分附加到每个字符串。
我需要输出为:
stuff/that/was/backed/up/file0.ext
stuff/that/was/backed/up/file1.ext
stuff/that/was/backed/up/file3.ext
而不是:
X:/mydata/backup/stuff/that/was/backed/up/file0
- 等等
路径可以是任何东西,所以我也不能使用硬编码的解决方案,比如在 Application.StartupPath
目录(我目前使用的目录)中使用 Split(path, "/", 2)
。
您可以使用 System.IO.Path
中的方法来操作路径字符串。
要分隔目录和文件名:
Dim filenameAndExtension As String = Path.GetFileName(fullPath)
Dim directory As String = Path.GetDirectoryName(fullPath)
您还可以使用 Path.GetFileName(directory)
获取目录路径的最后一部分。
合并目录和文件名:
Dim fullPath As String = Path.Combine(directory, filenameAndExtension)
经过多次纠缠和毫无帮助的评论后,我找到了解决方案:
Dim unitstring As String() = Split(TextBox2.Text, "\") 'separate directory names
Dim unitcount As Integer = Array.LastIndexOf(unitstring, Path.GetFileName(TextBox2.Text)) + 2 'get how far in the directory we are from the root.
Dim paths As New List(Of String) 'list to hold results
For Each x In IO.Directory.GetDirectories(TextBox2.Text, "*", SearchOption.AllDirectories) 'loop through all directories to get them in the format needed
Dim pathsplit As String() = Split(x, "\", unitcount) 'split from parent
paths.Add(pathsplit(unitcount - 1)) 'the last item in the array is what is needed.
Next
如果其他人需要这样的代码,请随时使用它。
我知道 IO.Directory.GetDirectories("X:/mydata/backup/stuff", "*", IO.SearchOption.AllDirectories)
可用于获取所有目录,但我需要弄清楚如何不将父部分附加到每个字符串。
我需要输出为:
stuff/that/was/backed/up/file0.ext
stuff/that/was/backed/up/file1.ext
stuff/that/was/backed/up/file3.ext
而不是:
X:/mydata/backup/stuff/that/was/backed/up/file0
- 等等
路径可以是任何东西,所以我也不能使用硬编码的解决方案,比如在 Application.StartupPath
目录(我目前使用的目录)中使用 Split(path, "/", 2)
。
您可以使用 System.IO.Path
中的方法来操作路径字符串。
要分隔目录和文件名:
Dim filenameAndExtension As String = Path.GetFileName(fullPath)
Dim directory As String = Path.GetDirectoryName(fullPath)
您还可以使用 Path.GetFileName(directory)
获取目录路径的最后一部分。
合并目录和文件名:
Dim fullPath As String = Path.Combine(directory, filenameAndExtension)
经过多次纠缠和毫无帮助的评论后,我找到了解决方案:
Dim unitstring As String() = Split(TextBox2.Text, "\") 'separate directory names
Dim unitcount As Integer = Array.LastIndexOf(unitstring, Path.GetFileName(TextBox2.Text)) + 2 'get how far in the directory we are from the root.
Dim paths As New List(Of String) 'list to hold results
For Each x In IO.Directory.GetDirectories(TextBox2.Text, "*", SearchOption.AllDirectories) 'loop through all directories to get them in the format needed
Dim pathsplit As String() = Split(x, "\", unitcount) 'split from parent
paths.Add(pathsplit(unitcount - 1)) 'the last item in the array is what is needed.
Next
如果其他人需要这样的代码,请随时使用它。