Home
VB.NET
Get File Size: FileInfo Example
Updated Jun 10, 2022
Dot Net Perls
File size. Sometimes in VB.NET programs we want to get the number of bytes in a file. FileInfo can return the file size. This value is a Long, but can usually be safely to an Integer.
Some steps. We create a new FileInfo instance with a file name. We then access the Length property to get a byte size of the file.
Integer
File
Example. First, to begin using FileInfo, it helps to import System.IO. We construct the FileInfo instance by passing a file name to its constructor.
Tip If the specified file does not exist, you will need to create it outside of the code to run the example.
Detail Once you obtain the FileInfo instance, you can access the Length property. This tells you how many bytes are in the file.
Here We append to the file and then measure its size after the append operation.
Detail This type is useful for acquiring file sizes—it does not require cumbersome loops or string conversions.
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
Before and after: 3, 20 Size increase: 17
Program notes. The initial file was only 3 bytes in length, while the file after the append operation was 20 bytes. This means the file increased in size by 17 bytes.
Summary. We looked at how you can obtain the size of a file using VB.NET. Further, we demonstrated how this measurement changes as the file is mutated on the disk.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 10, 2022 (simplify).
Home
Changes
© 2007-2025 Sam Allen