Home
Map
Get Directory SizeSum up the total file sizes of all the files in a directory by using FileInfo and its Length property.
VB.NET
This page was last reviewed on Jan 5, 2024.
Directory size. What is the total size of all files in a directory? The System.IO namespace in VB.NET can be used to answer this question—a couple Functions are needed.
With Directory.GetFiles, we can get an array of file names. And by using FileInfo and its Length property, we can sum up all the sizes for those files.
Example. It is necessary to import the System.IO namespace with an Imports directive at the top of the file. This allows the program to compile, and makes types easier to access.
Step 1 We call the Function GetDirectorySize with a path name relative to the working directory.
Step 2 In GetDirectorySize, we first call Directory.GetFiles. We use a wildcard pattern to match all files with all extensions.
Directory.GetFiles
Step 3 We use a For Each loop to sum up all the file sizes. Our For Each loop enumerates the file names in the array.
For
Step 4 To get the size of a file in bytes, we create a FileInfo, and then access its Length. This value is returned as a Long.
File Size
Step 5 We return the total size of all files. It may be helpful to cache this value, to avoid excessive IO operations.
Imports System.IO Module Module1 Sub Main() ' Step 1: call GetDirectorySize with a folder path. Dim size As Long = GetDirectorySize("programs\") Console.WriteLine(size) End Sub Function GetDirectorySize(path As String) As Long ' Step 2: get all files from directory. Dim files = Directory.GetFiles(path, "*.*") ' Step 3: sum up total size of all files in directory. Dim totalBytes = 0 For Each name as String in files ' Step 4: use FileInfo on each file path and access its Length property. Dim info = New FileInfo(name) totalBytes += info.Length Next ' Step 5: return total size in bytes of all files. Return totalBytes End Function End Module
60898499
Summary. It is sometimes useful to keep track of directory file sizes. This information can help us determine when to delete files, or issue some other sort of warning.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 5, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.