我尝试练习,搜索,但我找不到如何重命名所需文件夹中所有文件夹和子文件夹的解决方案。例如,我想循环遍历所有文件夹并添加“_ test”到最后,我搜索,练习,我没有找到任何好的解决方案,所以我问你,如果你有任何代码片段,或只是和想法。我开始创建一个文件夹中所有文件夹的数组:
Dim folderArray() As String = IO.Directory.GetDirectories(TextBoxPath.Text, "*", IO.SearchOption.AllDirectories)
For Each folder In folderArray
Dim infoParent As New IO.DirectoryInfo(folder)
Dim folderParent = infoParent.Parent.FullName
Dim folderName = folder.Split(IO.Path.DirectorySeparatorChar).Last()
FileSystem.Rename(folder, folderParent & "\" & folderName & "_Test")
Next
但是这不起作用,因为我重命名目录,所以数组无效(folderArray),因为它有旧的目录路径。
如果你有办法,我会接受建议,谢谢。
答案 0 :(得分:1)
这听起来像递归的工作。由于您不知道任何给定文件夹将包含多少个文件夹,或者文件夹结构可以有多少级别,因此您不能只循环它。相反,编写一个函数来解决整个问题的一个独立部分并递归该函数。我的VB 非常生锈,所以这可能不是100%有效(你肯定想调试一下),但这个想法是这样的:
Function RenameFolderAndSubFolders(ByVal folder as String)
' Get the sub-folders of the current folder
Dim subFolders() As String = IO.Directory.GetDirectories(folder, "*", IO.SearchOption.AllDirectories)
If subFolders.Length < 1 Then
'This is a leaf node, rename it and return
FileSystem.Rename(folder, folder & "_Test")
Return
End If
' Recurse on all the sub-folders
For Each subFolder in subFolders
RenameFolderAndSubFolders(subFolder)
' Rename the current folder once the recursion is done
FileSystem.Rename(subFolder, subFolder & "_Test")
Next
End Function
这里的想法很简单。给定文件夹名称,获取所有子文件夹。如果没有,请重命名该文件夹。如果有,请对它们递归相同的功能。这应该找到所有文件夹并相应地重命名它们。要启动该过程,只需在要重命名的目录树的根文件夹上调用该函数。
答案 1 :(得分:1)
我会尝试递归地确保它首先在最底层完成。 (可能不是100%正确的代码,但只是为了给出一般的想法)
Sub RenameFolderRecursive(path As String)
For Each f As String In IO.Directory.GetDirectories(path)
RenameFolderRecursive(f)
Next
IO.Directory.Move(path, path & "_test")
End Sub
看看是否有效。
答案 2 :(得分:0)
Sub RenameAll(ByVal sDir As String)
Try
For Each d As String In Directory.GetDirectories(sDir)
IO.Directory.Move(d, d & "_test")
RenameAll(d & "_test")
Next
Catch x As System.Exception
End Try
End Sub
这是递归函数,可以完成你需要的工作。
答案 3 :(得分:0)
Private Sub RenameAllFolds(d As String)
Dim subfolds() As String = IO.Directory.GetDirectories(d)
If subfolds.Count = 0 Then
IO.Directory.Move(d, d & "_Test")
Else
For Each dir As String In subfolds
RenameAllFolds(dir)
Next
IO.Directory.Move(d, d & "_Test")
End If
End Sub
Sub Main()
Dim inf As String = "C:\renametest"
Dim folds() As String = IO.Directory.GetDirectories(inf)
For Each f As String In folds
RenameAllFolds(f)
Next
Console.ReadKey()
End Sub