How to find whether the given directory is empty (in three ways)
Posted on January 4, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | 'File/Folder Handling - How to find whether the given directory is empty (in three ways) Option Explicit 'Using Dir: Public Function IsDirEmptyUsingDir(ByVal sPath As String) As Boolean 'On Error Resume Next Dim dirname As String, iCount As Integer If Right$(sPath, 1) <> "\" Then sPath = sPath & "\" dirname = Dir$(sPath & "*.*", vbDirectory) If Len(dirname) = 0 Then Call MsgBox("The Directory doesn't exist.", vbInformation, App.Title) Else Do While Len(dirname) If dirname = "." Or dirname = ".." Then ' Exclude the "." and ".." entries. Else ' This is a regular file or a directory. iCount = iCount + 1 End If dirname = Dir$ Loop End If IsDirEmptyUsingDir = (iCount = 0) End Function 'How can I call this function: 'Debug.Print IsDirEmptyUsingDir("C:\Temp\b1") 'Using FSO: Public Function IsDirEmptyUsingFSO(ByVal sPath As String) As Boolean 'Set a reference to "Microsoft Scripting Runtime" Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject If Not FSO.FolderExists(sPath) Then Call MsgBox("The Directory doesn't exist.", vbInformation, App.Title) GoTo ExitHere End If IsDirEmptyUsingFSO = ((FSO.GetFolder(sPath).Files.count + FSO.GetFolder(sPath).SubFolders.count) = 0) ExitHere: Set FSO = Nothing End Function 'How can I call this function: 'Debug.Print IsDirEmptyUsingFSO("C:\Temp\b1") 'Using API: Declare Function PathIsDirectoryEmpty Lib "shlwapi.dll" Alias "PathIsDirectoryEmptyA" _ (ByVal pszPath As String) As Long Public Function IsDirEmptyUsingAPI(ByVal sPath As String) As Boolean IsDirEmptyUsingAPI = PathIsDirectoryEmpty(sPath) End Function 'How can I call this function: 'Debug.Print IsDirEmptyUsingAPI("C:\Temp\b1") |