5.4. Calculate the Size of a Directory

Problem

You need to calculate the size of all files contained in a directory (and, optionally, its subdirectories).

Solution

Examine all the files in a directory and add together their FileInfo.Length properties. Use recursive logic to include the size of files in contained subdirectories.

How It Works

The DirectoryInfo class does not provide any property that returns size information. However, you can easily calculate the size of all files contained in a directory by adding together each file's size, which is contained in the FileInfo.Length property.

The Code

The following example calculates the size of a directory and optionally examines subdirectories recursively.

Imports System Imports system.IO Namespace ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.