开发者

How to check a subfolder existence VB6

开发者_StackOverflow中文版

Ive been searching for this for like decades with no success. I need to find out if a subdfolder that i ve given the name is exist..

For i = 0 To 3 'got 4 different loc to check sub folders
    Set f = fso.GetFolder(backupdir(i)) 
    Set sf = f.SubFolders
    For Each fr In sf 'for each folder in sub folder
        Do Until fr = "" Or fr = Null 
            If fso.FolderExists(fr.SubFolders) Then 
            'if more sub folders exist i wanna make sure
            'that i can get their subfolders too
            'till there is no sub folder left..
                sf = fr
            End If
        Loop
    Next fr
Next i


Actions like traversing the folders-of-a-folder-of-a-folder... is called recursing.

The FindFirstFile: Recursive Search for Folders Using a Folder Mask (minimal code) example here shows how to do this quickly with the windows API.


Check this code.

Dim FolderList As String

Private Sub SubCheck1(folderToCheck As String)
   Dim fso, f, f1, s, sf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderToCheck)
   Set sf = f.SubFolders
   For Each f1 In sf
      FolderList = FolderList & "|" & f1.Name
      Call SubCheck1(f1.Path)
   Next
End Sub

Private Sub Form_Load()
   Call SubCheck1("c:\folderToSearch")
   Debug.Print FolderList
End Sub

This code gets all the subfolders in the specified directory(c:\folderToSearch in this case) and writes them into the string FolderList with a "|" seperator.

You can also use an array instead of separating folder names with a "|". Or you can add the code below after the Debug.Print FolderList line in Form_Load to get an array:

myArray = split(FolderList, "|")


You can "recurse" subfolders with a collection and standard Dir function in 20 lines of code like this

Private Sub Command1_Click()
    Dim vElem           As Variant

    For Each vElem In pvGetFolders("C:\TEMP")
        Debug.Print vElem
    Next
End Sub

Private Function pvGetFolders(ByVal sRoot As String) As Collection
    Dim lIdx            As Long
    Dim sFile           As String

    Set pvGetFolders = New Collection
    pvGetFolders.Add sRoot
    Do While lIdx < pvGetFolders.Count
        lIdx = lIdx + 1
        sFile = Dir(pvGetFolders.Item(lIdx) & "\*.*", vbDirectory)
        Do While LenB(sFile) <> 0
            If sFile <> "." And sFile <> ".." Then
                sFile = pvGetFolders.Item(lIdx) & "\" & sFile
                If (GetAttr(sFile) And vbDirectory) <> 0 Then
                    pvGetFolders.Add sFile
                End If
            End If
            sFile = Dir
        Loop
    Loop
    pvGetFolders.Remove 1
End Function


You could use WMI. You could search in CIM_Directory, I believe the field name is "name", and if it contains the folder or partially the foldername you are looking for, return the full name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜