Help Man Help Man - 5 months ago 17
Vb.net Question

Get count of similar files in a folder

I have a file, lets call it "myFile.txt", in a folder. There are also going to be other files named "myFile1.txt, myFile2.txt, myFile3.txt, myFile4.txt" in that same folder and so forth. I want to check that folder and count how many times "myFile" shows up in that folder no matter what the extension or the number after "myFile". Here's what I have so far, but it's not getting what I want:

Dim MyFiles1() As String = IO.Directory.GetFiles("filepath", "myFile.txt")

Answer

I whipped this up and tested it in Visual Studio:

'Get a list of files from a directory you designate
    Dim counter As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
    counter = My.Computer.FileSystem.GetFiles("C:\YOURDIR")

'Declare your file name
    Dim myfile As String = "YOURFILE"

'Create count dim
    Dim Occurrences As Integer = 0

'Check all files in the array and check them against our filename
    For Each File As String In counter
        If File.Contains(myfile) Then
'If a file is found, add +1
            Occurrences = Occurrences + 1
        End If
    Next
'Display total count
    MsgBox("number of files is " & Occurrences)

This will go and search the path you designate. It will check all files like your filename in the dir. If it finds one, it will count it. This also checks for case insensitive names as well so you can get all variants of your file name.