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.
FileInfo
To get all FileInfos
from a directory, we can use the GetFileSystemInfos
method. This can make some file-handling code clearer.
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
.
FileInfo
—this allows us to get the file size. We use the Length
property and a long value.Console.WriteLine
method. The sizes are in bytes.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);LENGTH IN BYTES: 60
GetFileSystemInfos
We can get an array of FileSystemInfo
and then get each individual FileInfo
. We use the GetFileSystemInfos
method.
GetFileSystemInfos
.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
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.