Get File Size (FileInfo Length)
This page was last reviewed on Sep 13, 2023.
Dot Net Perls
FileInfo Length. FileInfo has a Length property. It returns the size of a file in bytes. We use FileInfo and the Length property to measure file sizes.
Notes, FileInfo. To get all FileInfos from a directory, we can use the GetFileSystemInfos method. This can make some file-handling code clearer.
An example. FileInfo is useful if your program modifies files, and you want to see how many bytes have been added or removed. The Length often can be safely cast to an int.
long, ulong
Part 1 The code creates a new FileInfo—this allows us to get the file size. We use the Length property and a long value.
Part 2 We print the size of the file with the Console.WriteLine method. The sizes are in bytes.
byte, sbyte
Tip Make sure to update the path to a file that exists on your computer before running the program.
using System; using System.IO; const string fileName = @"C:\programs\file.txt"; // Part 1: create new FileInfo get Length. FileInfo info = new FileInfo(fileName); long length = info.Length; // Part 2: print length in bytes. Console.WriteLine("LENGTH IN BYTES: {0}", length);
GetFileSystemInfos. We can get an array of FileSystemInfo and then get each individual FileInfo. We use the GetFileSystemInfos method.
Part 1 We get the info objects for the specified I rectory. We call GetFileSystemInfos.
Part 2 We loop over the objects and get each individual FileInfo and then access the Length. We sum these values and return the sum.
using System; using System.IO; class Program { static int GetDirectorySize(string path) { // Part 1: get info. DirectoryInfo directoryInfo = new DirectoryInfo(path); FileSystemInfo[] array = directoryInfo.GetFileSystemInfos(); // Part 2: sum all FileInfo Lengths. int sum = 0; for (int i = 0; i < array.Length; i++) { FileInfo fileInfo = array[i] as FileInfo; if (fileInfo != null) { sum += (int)fileInfo.Length; } } return sum; } public static void Main() { Console.WriteLine("SIZE: {0}", GetDirectorySize(@"C:\programs\")); } }
SIZE: 96035
Exceptions. It is common to have to handle exceptions when files are being used. They may be missing, corrupted or not accessible because of security issues.
We retrieved the length of files using the FileInfo class and its Length property. This uses a long value and does not require you to read and process the entire file.
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 Sep 13, 2023 (edit).
© 2007-2024 Sam Allen.