# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB - List All The Files In A Directory

## manavo11

This shows the filenames and not the total number of files in a directory.

----------


## manavo11

Another way (API) :


VB Code:
'Create a form with a command button (command1), a list box (list1)
'and four text boxes (text1, text2, text3 and text4).
'Type in the first textbox a startingpath like c:\
'and in the second textbox you put a pattern like *.* or *.txt
 Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
 Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100
 Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type
 Private Type WIN32_FIND_DATA
    dwFileAttributes As Long
    ftCreationTime As FILETIME
    ftLastAccessTime As FILETIME
    ftLastWriteTime As FILETIME
    nFileSizeHigh As Long
    nFileSizeLow As Long
    dwReserved0 As Long
    dwReserved1 As Long
    cFileName As String * MAX_PATH
    cAlternate As String * 14
End Type
Function StripNulls(OriginalStr As String) As String
    If (InStr(OriginalStr, Chr(0)) > 0) Then
        OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
    End If
    StripNulls = OriginalStr
End Function
 Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
    'KPD-Team 1999
    'E-Mail: [email]KPDTeam@Allapi.net[/email]
    'URL: [url]http://www.allapi.net/[/url]
     Dim FileName As String ' Walking filename variable...
    Dim DirName As String ' SubDirectory Name
    Dim dirNames() As String ' Buffer for directory name entries
    Dim nDir As Integer ' Number of directories in this path
    Dim i As Integer ' For-loop counter...
    Dim hSearch As Long ' Search Handle
    Dim WFD As WIN32_FIND_DATA
    Dim Cont As Integer
    If Right(path, 1) <> "\" Then path = path & "\"
    ' Search for subdirectories.
    nDir = 0
    ReDim dirNames(nDir)
    Cont = True
    hSearch = FindFirstFile(path & "*", WFD)
    If hSearch <> INVALID_HANDLE_VALUE Then
        Do While Cont
        DirName = StripNulls(WFD.cFileName)
        ' Ignore the current and encompassing directories.
        If (DirName <> ".") And (DirName <> "..") Then
            ' Check for directory with bitwise comparison.
            If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
                dirNames(nDir) = DirName
                DirCount = DirCount + 1
                nDir = nDir + 1
                ReDim Preserve dirNames(nDir)
            End If
        End If
        Cont = FindNextFile(hSearch, WFD) 'Get next subdirectory.
        Loop
        Cont = FindClose(hSearch)
    End If
    ' Walk through this directory and sum file sizes.
    hSearch = FindFirstFile(path & SearchStr, WFD)
    Cont = True
    If hSearch <> INVALID_HANDLE_VALUE Then
        While Cont
            FileName = StripNulls(WFD.cFileName)
            If (FileName <> ".") And (FileName <> "..") Then
                FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
                FileCount = FileCount + 1
                List1.AddItem path & FileName
            End If
            Cont = FindNextFile(hSearch, WFD) ' Get next file
        Wend
        Cont = FindClose(hSearch)
    End If
    ' If there are sub-directories...
    If nDir > 0 Then
        ' Recursively walk into them...
        For i = 0 To nDir - 1
            FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(i) & "\", SearchStr, FileCount, DirCount)
        Next i
    End If
End Function
Sub Command1_Click()
    Dim SearchPath As String, FindStr As String
    Dim FileSize As Long
    Dim NumFiles As Integer, NumDirs As Integer
    Screen.MousePointer = vbHourglass
    List1.Clear
    SearchPath = Text1.Text
    FindStr = Text2.Text
    FileSize = FindFilesAPI(SearchPath, FindStr, NumFiles, NumDirs)
    Text3.Text = NumFiles & " Files found in " & NumDirs + 1 & " Directories"
    Text4.Text = "Size of files found under " & SearchPath & " = " & Format(FileSize, "#,###,###,##0") & " Bytes"
    Screen.MousePointer = vbDefault
End Sub

----------


## manavo11

The Dir way :


VB Code:
'Just add a listbox (List1)
 Private Sub ListFiles(strPath As String, Optional Extention As String)
'Leave Extention blank for all files
    Dim File As String
    
    If Right$(strPath, 1) <> "\" Then strPath = strPath & "\"
    
    If Trim$(Extention) = "" Then
        Extention = "*.*"
    ElseIf Left$(Extention, 2) <> "*." Then
        Extention = "*." & Extention
    End If
    
    File = Dir$(strPath & Extention)
    Do While Len(File)
        List1.AddItem File
        File = Dir$
    Loop
End Sub
 Private Sub Form_Load()
ListFiles "C:\", "txt"
End Sub

----------


## thebloke

> _Originally posted by manavo11_ 
> *This shows the filenames and not the total number of files in a directory.*


I'll take the easy route! Works a treat. Thanks.

 :Thumb:

----------


## manavo11

> _Originally posted by thebloke_ 
> *I'll take the easy route! Works a treat. Thanks.
> 
> *


Anytime  :Thumb:

----------


## positive+

Yup...this is nice, thank's   :Thumb:   :Smilie:

----------


## DarkX_Greece

Nice code example manavo11!

Thanks, i need it!

----------


## dos5731

it works here.

----------


## RedJam

> The Dir way :
> 
> 
> VB Code:
> 'Just add a listbox (List1)
>  Private Sub ListFiles(strPath As String, Optional Extention As String)
> 'Leave Extention blank for all files
>     Dim File As String
>     
> ...



Hello,

Thank for the above code, works a treat but I'm just wondering if anyone could help me out with a similarly easy way to do the same but to list the names of directories ("folders") within a directory?

So, the above code works great, it lists all the files of whatever type in say "C:\folder1".

What I need is code to list all the directories within "C:\folder1", not including subdirectories.

If anyone could help I would be much obliged.

Thanks in advance.

----------


## Hack

> What I need is code to list all the directories within "C:\folder1", not including subdirectories.




```
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
    ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Private Const LB_DIR = &H18D

Private Const DDL_DIRECTORY = &H10
Private Const DDL_ARCHIVE = &H20
Private Const DDL_EXCLUSIVE = &H8000

Private Sub Command1_Click()
    List1.Clear
    SendMessage List1.hwnd, LB_DIR, DDL_EXCLUSIVE Or DDL_DIRECTORY, ByVal "C:\folder1\*.*"
End Sub
```

----------


## RedJam

Cool, cheers mate  :Smilie: 

Had to tweak it a bit of course but working now, thanks.

J

----------


## Paul M

Here is my shot it gets all files in sub directories to!


vb Code:
Public Function ListFiles(FolderPath As String, Extension As String, LstObj As ListBox)
Dim i As Long
Dim FolderName As String
Dim DirNames() As String
Dim SubDirectories As Long
 'List files in the main/first folder
FolderName = Dir(FolderPath & "\" & Extension, vbNormal)
 Do While FolderName <> vbNullString
    LstObj.AddItem FolderPath & "\" & FolderName
    FolderName = Dir()
Loop
 'Get the sub directories
FolderName = Dir(FolderPath & "\*.*", vbDirectory)
 Do While FolderName <> vbNullString
    If FolderName <> "." And FolderName <> ".." Then
        SubDirectories = SubDirectories + 1
        ReDim Preserve DirNames(1 To SubDirectories)
        DirNames(SubDirectories) = FolderName
    End If
        FolderName = Dir()
Loop
  For i = 1 To SubDirectories
        ListFiles FolderPath & "\" & DirNames(i), Extension, LstObj
Next i
End Function


vb Code:
Private Sub Command1_Click()
ListFiles "C:\SomeFolder", "*.img", List1
End Sub

Sorry for the bump.

----------


## goldenix

just a note that none of the codes work in 2008.

----------


## manavo11

The Visual Studio 2008 you mean? It won't work, it's VB6 code. That's why it's in the VB6 and earlier codebank  :Wink:

----------


## indigofish

[QUOTE=Paul M;2973969]Here is my shot it gets all files in sub directories to!

[QUOTE]

Hi

Apologies in advance for needing to ask a dumb question, but I'm pretty new to this and flying solo. I'm a tech writer, not a programmer, and have been making a few half-hearted attempts to learn VB so that I can have more control over my word docs. Problem is I am still at the starting blocks and need to catalogue all the template files in a directory, including all sub-dirs, so this post is very interesting to me, but I don't know what to do with the code!

I know enough to open the VB editor in word, and paste it into a code window, but I don't know how to name it, or how to call it. Also, there's the question of the sub tacked on at the end and how to deal with it (where does it go, etc).

Ok so banish me to the sandpit, but if someone would be kind enough to give me some steps on how to use this code first, I'll be extremely grateful. My other option is to hand type out several thousand file names.

(PS While registering for the forum, I noticed an office forum, so i will head over there and read up, but this post is the first one i found covering exactly my required task)

----------


## mustiback

Thanks For aLL!

----------


## tamalero

Hello there, Thanks alot for your code, 
just a quick question...
is there a way to list files in a directory but get the contents  arranged in some ways like "last modified" or "by name" ?

----------


## manavo11

I'm not sure if there is a way to get the list of files in a specific sorted order. However, since you can get all files, you can then read any information you want for each file (last modified, size, etc) and then do the sorting yourself after you get the whole list!

----------


## jason8100

Hi I am making a search engine in VB6, your code works but I also need to list all files in subdirs as well. I already searched on google but I couldnt find anything. ( except the ones that cause your whole project to crash:S ) Do you know how to achieve this?

Thanks in advance,
Jason

----------


## manavo11

If you look at this thread: http://www.vbforums.com/showthread.php?t=244880 it's code for listing all sub-directories. If you combine the two, then you have exactly what you want  :Smilie:

----------


## jason8100

> If you look at this thread: http://www.vbforums.com/showthread.php?t=244880 it's code for listing all sub-directories. If you combine the two, then you have exactly what you want


I have tryed the code but don't get it working. It just gives a number of folders, don't know what to do with it. Could you please help me.

Thanks in advance,
Jason

----------


## Dennijr

> The Dir way :
> 
> 
> VB Code:
> 'Just add a listbox (List1)
>  Private Sub ListFiles(strPath As String, Optional Extention As String)
> 'Leave Extention blank for all files
>     Dim File As String
>     
> ...





> just a note that none of the codes work in 2008.


this code is pretty close, the following is what i turned it into and used, in vb.net 2008:



```
Dim file As String
        file = Dir$("D:\Documents and Settings\Compaq_Owner\My Documents\My Pictures\cards\*.png")
        Do While Len(file)
            ListBox2.Items.Add(Mid(file, 1, InStr(file, ".") - 1))
            file = Dir$()
        Loop
```

----------


## techker

cold we modify this for viewing the images?

----------


## manavo11

You could specify an extension. It is mentioned in the examples if you read through them carefully.

----------


## techker

> You could specify an extension. It is mentioned in the examples if you read through them carefully.


well itryed just this but it shows nothing

Dim file As String
        file = Dir$("D:\Documents and Settings\Compaq_Owner\My Documents\My Pictures\cards\*.png")
        Do While Len(file)
            ListBox2.Items.Add(Mid(file, 1, InStr(file, ".") - 1))
            file = Dir$()
        Loop

----------


## manavo11

Try starting with the code from the third post: http://www.vbforums.com/showpost.php...79&postcount=3

It seems like the most similar to the code you have. Compare it, find the differences and I'm sure you'll be able to work it out  :Smilie:

----------


## techker

> The Dir way :
> 
> 
> VB Code:
> 'Just add a listbox (List1)
>  Private Sub ListFiles(strPath As String, Optional Extention As String)
> 'Leave Extention blank for all files
>     Dim File As String
>     
> ...


why do i get errors?
i added a list box named it List1

Error	1	Optional parameters must specify a default value.	C:\Users\TECHKER\Desktop\PROGRAMMING\PROJECTS\WindowsApplication1\WindowsApplication1\Form5.vb	3	74	WindowsApplication1

Error	2	'Public ReadOnly Property Right() As Integer' has no parameters and its return type cannot be indexed.	C:\Users\TECHKER\Desktop\PROGRAMMING\PROJECTS\WindowsApplication1\WindowsApplication1\Form5.vb	7	12	WindowsApplication1

Error	4	'Public Property Left() As Integer' has no parameters and its return type cannot be indexed.	C:\Users\TECHKER\Desktop\PROGRAMMING\PROJECTS\WindowsApplication1\WindowsApplication1\Form5.vb	11	16	WindowsApplication1

Error	5	Type character '$' does not match declared data type 'Integer'.	C:\Users\TECHKER\Desktop\PROGRAMMING\PROJECTS\WindowsApplication1\WindowsApplication1\Form5.vb	11	16	WindowsApplication1

Error	6	'AddItem' is not a member of 'System.Windows.Forms.ListBox'.	C:\Users\TECHKER\Desktop\PROGRAMMING\PROJECTS\WindowsApplication1\WindowsApplication1\Form5.vb	17	13	WindowsApplication1

----------


## si_the_geek

You are getting errors because you are in the wrong place... this is the VB6 Codebank, but you are using VB.Net

Post #22 is the only thing from this thread that you should consider using - for anything else (including help fixing issues with it) you should post in the VB.Net forum.

----------


## davis1d0

> The Dir way :
> 
> 
> VB Code:
> 'Just add a listbox (List1)
>  Private Sub ListFiles(strPath As String, Optional Extention As String)
> 'Leave Extention blank for all files
>     Dim File As String
>     
> ...


I'm attempting to use this code, it should do everything I need, but my Listbox comes up blank.  Which was my problem before and hoped this code would help me fix this.  I'm teaching myself how to use VB6 so please spell things out to me as though I were a little kid.  Thank you.

----------


## manavo11

> I'm attempting to use this code, it should do everything I need, but my Listbox comes up blank.  Which was my problem before and hoped this code would help me fix this.  I'm teaching myself how to use VB6 so please spell things out to me as though I were a little kid.  Thank you.


Unless we see exactly your code, we won't be able to help! You can create a new thread in the Visual Basic 6 and Earlier forum to get more help  :Smilie:

----------


## Crysis_2

vb Code:
Public Shared Sub GET_ALL_FILES(ByVal Folder As String, ByVal List As ListBox)        For Each Files As String In My.Computer.FileSystem.GetFiles(Folder)            List.Items.Add(Files)        Next    End Sub
There is my code. It work`s great!

----------


## asto

how attribute first of the list to text1.text (as example)

then delete first of the list

and second of the list will be first ............ect

----------


## normale15

> This shows the filenames and not the total number of files in a directory.


Hi Manavo11,

Could you please write this in VB5 code.

Thanks

Normale15

----------


## Bobbles

> Hi Manavo11,
> 
> Could you please write this in VB5 code.
> Thanks
> Normale15


Here are a couple of links on how to do that -
http://www.devx.com/vb2themax/Tip/18390
http://www.vb-helper.com/vb6tovb5.htm
Rob
PS I hate people telling us to upgrade to VB.NET, however the upgrade from VB5 to VB6 is highly recommended (I won't clutter up this thread, with the reasons)

----------


## Arnoutdv

> Hi Manavo11,
> 
> Could you please write this in VB5 code.
> 
> Thanks
> 
> Normale15


The sample code in post #2 and post #3 should also work in VB5.

----------


## hwoarang

Maybe that module containing lots of FileSystem routines will be helpfull.

----------


## normale15

Thanks to all that have replied.

The folder structure I am working with is - drive letter/folder level1 (single folder)/folder level 2 (single folder)/folder level 3(multiple folders)/folder level 4 (multiple folders)/multiple filenames in each folder at level 4.

What I am needing to do is to return, on a form, a list of all files showing part of the path (including the extension) but only that part of the path showing folder level 3, folder level 4, and the filename. 

The drive letter is not to be hard coded as the exe could be run from any drive letter.

And of course using VB5

----------


## hwoarang

> Thanks to all that have replied.
> 
> The folder structure I am working with is - drive letter/folder level1 (single folder)/folder level 2 (single folder)/folder level 3(multiple folders)/folder level 4 (multiple folders)/multiple filenames in each folder at level 4.
> 
> What I am needing to do is to return, on a form, a list of all files showing part of the path (including the extension) but only that part of the path showing folder level 3, folder level 4, and the filename. 
> 
> The drive letter is not to be hard coded as the exe could be run from any drive letter.
> 
> And of course using VB5


You can modify DirSize function from my archive above to return an array of file and folders. And then filter/use it as you want. Or filter right "in place" before return.

----------


## normale15

Sorry Hwoarang, I cannot find your DirSize archive. Where is it please?

----------


## hwoarang

> Sorry Hwoarang, I cannot find your DirSize archive. Where is it please?


FileSystemFunctions.zip attached - 3 posts above. There is a VB6 project inside with a class that contains DirSize function. You can try to change it for your requirements - it should be pretty easy.

----------


## farhanleos

Dear Paul,

IF you can help me out it will be great 
actually i am trying to get a code which will work in share drive , 
to get the list of All Folders  Highglited in bold font
All subfolders if any 
and all type of files 
the last modified date

----------


## Peter Swinkels

```
Option Explicit

Public Declare Function SafeArrayGetDim Lib "oleaut32.dll" (ByRef saArray() As Any) As Long

Public Function GetFiles(Path As String) As String()
Dim Files() As String
Dim Item As String

   If Not Right$(Path, 1) = "\" Then Path = Path & "\"
   Path = Path & "*.*"

   Item = Dir$(Path, vbArchive Or vbHidden Or vbReadOnly Or vbSystem)
   Do Until Item = vbNullString
      If SafeArrayGetDim(Files()) = 0 Then
         ReDim Files(0 To 0) As String
      Else
         ReDim Preserve Files(LBound(Files()) To UBound(Files()) + 1) As String
      End If

      Files(UBound(Files())) = Item
      Item = Dir$()
   Loop

   If SafeArrayGetDim(Files()) = 0 Then ReDim Files(0 To 0) As String

   GetFiles = Files
End Function

Public Sub Main()
Dim Item As Variant

   For Each Item In GetFiles("C:\Windows\System32")
      Debug.Print Item
   Next Item
End Sub
```

----------


## darjeeling

There is also '*clsFileAnalyzer v2.5*' from NightWolf.
http://www.planet-source-code.com/vb...67832&lngWId=1
I use this class on many projects.

----------


## DryBone

Ooops

----------

