2

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!

Technologuy
  • 131
  • 3
  • 16

1 Answers1

5

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.

sab669
  • 3,984
  • 8
  • 38
  • 75
  • 1
    Thank's a lot,that's exactly what I wanted. – Technologuy Aug 28 '15 at 20:09
  • 1
    Don't want to be that guy, but I think `*.*` would only get files with a dot inside their name. So files like "ImHiding" which have no and filetype defined wouldn't be counted, would they? ..just a little exploit unlikely to happen. – Luke Jul 10 '17 at 05:52
  • 3
    @Luke I thought you might be right, but I just tested it. It still finds extension-less files. [See screenshot of output here](http://i.imgur.com/nJlliD4.png). – sab669 Jul 10 '17 at 11:56
  • 1
    That's unexpected. +1 for trying out :-) – Luke Jul 10 '17 at 12:32
  • @Luke [This](http://referencesource.microsoft.com/#mscorlib/system/io/filesystemenumerable.cs,c026d69ba22f8681,references) is the method that gets called on the string. I'm not sure *exactly* what `searchPattern.TrimEnd(Path.TrimEndChars)` does but I'd wager it removes any asterisks, and then sees that it's just a single `.` which gets replaced with a single `*` in the `if` statement. But yes, unexpected IMO. – sab669 Jul 10 '17 at 12:39