
You want to acquire the file size of a file you are manipulating in the VB.NET programming language; the FileInfo type in the System.IO namespace provides for this functionality. By creating a new FileInfo instance on a file name, you can access the Length property to get a byte size of the file. Here, we describe and demonstrate the FileInfo type when used in this fashion.
First, to begin using the FileInfo type, it helps to include the System.IO namespace at the top using the "Imports System.IO" directive. In this example, we first construct the FileInfo instance by passing a file name to its constructor. If the specified file does not exist, you will need to create it outside of the code to run the example. Once you obtain the FileInfo instance, you can access the Length property, as well as many other properties. The Length property tells you how many bytes are in the file. Here, we append to the file and then measure its size after the append operation, demonstrating correctness.
Program that uses Length and FileInfo [VB.NET]
Imports System.IO
Module Module1
Sub Main()
' Get file info for test.txt.
' ... Create this file in Visual Studio and select Copy If Newer on its properties.
Dim info As New FileInfo("test.txt")
' Get length of the file.
Dim length As Long = info.Length
' Add more characters to the file.
File.AppendAllText("test.txt", " More characters.")
' Get another file info.
' ... Then get the length.
Dim info2 As New FileInfo("test.txt")
Dim length2 As Long = info2.Length
' Show how the size changed.
Console.WriteLine("Before and after: {0}, {1}", length, length2)
Console.WriteLine("Size increase: {0}", length2 - length)
End Sub
End Module
Output
(Will change each run.)
Before and after: 3, 20
Size increase: 17
Results. The program shows that the initial file was only three bytes in length, while the file after the append operation was 20 bytes, meaning the file increased in size by 17 bytes. This indicates that the Length differential is correct for this program, making this a useful way to determine file size changes in the VB.NET language.
In this article, we looked at how you can obtain the size of a file using the VB.NET programming language. Further, we demonstrated how this measurement changes as the file is mutated on the disk, indicating correctness. The FileInfo type is useful for acquiring file sizes, and it does not require cumbersome loops or string conversions to determine this information.
File Handling