Wednesday, October 27, 2021

[VB.net][example] Get total files size of a directory

 For example, i have a directory tree (# is a folder):


  • #root (C://root/) -----------0kb
    • #hidden 
      • 0byte.txt -------------0kb
      •    - 2bytes.txt --------2kb
      • hidden.txt ------------13kb
    • #noChild 
    • #normal 
      • 0byte.txt -------------0kb
      • 2bytes.txt ------------2kb
      • hidden.txt ------------13kb


solution

imports System.IO

Class test

  Private function getDirFilesSize(ByVal rootPath as String, Optional ByRef size As Long=0) As Long

    if directory.Exists(rootPath) Then

                Dim di As DirectoryInfo = New DirectoryInfo(path) 

      Dim folderInfo As DirectoryInfo = new IO.DirectoryInfo(rootPath)

      'For Each fileInfo in In folderInfo.GetFiles: size += fileInfo.Length

                 For Each fileInfo in In di.GetDirectories("*.*", SearchOption.AllDirectories) : size += fileInfo.Length 

      Next

      'For Each subFolderInfo In folderInfo.GetDirectories: getDirFilesSize(subFolderInfo.FullName, size)

For Each subFolderInfo In di.GetFiles("*.*", SearchOption.AllDirectories): getDirFilesSize(subFolderInfo.FullName, size) 

      Next 

    End if

    Return size

  End function

End Class


call the function getDirFilesSize("C://root/") would get the result as 30.

No comments :

Post a Comment