Technologuy
Technologuy

Reputation: 131

Counting all files in folder and subfolder

I am using visual basic and I want to count all the files that exist in a folder and in its subfolders.. I tried this :

Dim counter = My.Computer.FileSystem.GetFiles("C:\Folder") MsgBox("number of files is " & CStr(counter.Count))

but it only counts files in the C:\Folder and not in C:\Folder\Sub-Folder\AnotherSubFolder What should I do? Thank's for help!

Upvotes: 2

Views: 9741

Answers (1)

sab669
sab669

Reputation: 4104

Use Directory.GetFiles() as defined here: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx

So you'd just use

Dim counter As Integer = Directory.GetFiles(someString, "*.*", SearchOption.AllDirectories).Length;
MsgBox("Number of files is : " + counter)

someString being the top-level directory you want to start at

"*.*" being the search pattern you want to match. This gets all files. If you wanted only text files, for example, you could do "*.txt".

SearchOption enum has two options: AllDirectories or TopDirectoryOnly if you're only interested in the exact directory passed, obviously.

Upvotes: 5

Related Questions