File Size in VB.NET
- VB.NET requires the .NET framework in order for you to develop .NET applications. The .NET framework provides a managed execution environment, simplified development and integration with other programming languages not just in VB. One of the main purposes of the framework is to provide a consistent object-oriented programming environment whether object code is stored and executed locally or remotely. Microsoft offers documentation for the .NET framework, including an extensive class library reference, conceptual overviews and step-by-step procedures to get you started.
- The System.IO namespace contains object types that allow reading and writing to files and data streams such as a file or directory. In addition to reading the size of a file with this namespace, you can also use the “FileSystemWatcher” class to raise an event and execute code when a directory or file changes. Another class that can be useful when working with files is the “DriveInfo” to retrieve access to information on a drive before reading file sizes.
- The “FileInfo” class provides properties and instance methods for the creation, copying, deletion, moving and opening of files. The class exposes many members such as getting file attributes with the “Attributes” property. Before reading a file size you may consider looking for the file to see if it exists. You can use the “Exists” property of this class to get a value indicating whether the file exists.
- Use the “Length” property of the “FileInfo” class to get the size, in bytes, of a file. The following is an example of a console project that will display the file sizes in the “C:\Temp” directory:
Imports System.IO
Module Module1
Sub Main()
Dim di As New DirectoryInfo("c:\Temp\")
Dim fiArr As FileInfo() = di.GetFiles()
Dim f As FileInfo
Console.WriteLine("The directory {0} contains the following files:", di.Name)
For Each f In fiArr
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length)
Next f
Console.ReadLine()
End Sub
End Module