Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly count the number of files in a folder

Tags:

file

count

vb.net

I am making a list of folders, where each folder needs only a few properties, so I'm using the Class below. However, no matter the folder, the FilesInFolder property is alway 5 more than the actual number of files in the folder.

Can someone please help me find out what is wrong? Thanks.

Public Class Single_Action_Folder

    Public ReadOnly FullName As String = ""
    Public ReadOnly Name As String = ""
    Public ReadOnly FilesInFolder As Integer = 0
    Public ReadOnly Exists As Boolean = False

    '**
    ' Constructor
    '*
    Public Sub New(Optional dir As DirectoryInfo = Nothing)

        ' First check that a directory has been specified
        If dir Is Nothing Then Exit Sub

        ' Populate the class properties
        FullName = dir.FullName
        Name = dir.Name
        FilesInFolder = dir.GetFiles().Count
        Exists = dir.Exists

    End Sub

End Class
like image 853
David Gard Avatar asked Dec 09 '22 16:12

David Gard


2 Answers

So the issue here is that FilesInFolder = dir.GetFiles().Count was counting hidden files. Even though I've set Windows folder options to show hidden files/folders, they were not shown as they were things like album art. The following line sorted my issue.

FilesInFolder = Directory.GetFiles(FullName, "*.mp3").Count

I am wondering though, if there is a way to count more than one file type? I.e MP3 and WMA? If anyone happens to know, I'd apprciate a comment.

like image 170
David Gard Avatar answered Dec 11 '22 05:12

David Gard


Check you do not have hidden files in tested directories. I check your code on my PC and it is working good.

like image 37
Piotr Stapp Avatar answered Dec 11 '22 06:12

Piotr Stapp