C# FileInfo Length, Get File SizeUse the Length property on the FileInfo type. Length gets file sizes as long values.
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.
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.
Tip Make sure to update the path to a file that exists on your computer before running the program.
C# program that gets file size
using System; using System.IO; class Program { static void Main() { 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.
C# program that gets directory size
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.
A summary. 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.
© 2007-2022 sam allen.
see site info on the changelog.