C# FileInfo Length, Get File SizeThis C# example uses the Length property on the FileInfo type. Length gets file sizes as long values.
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, both before and after. We easily get the file size.FileInfo
FileInfo is useful if your program modifies files, and you want to see how many bytes have been added or removed. We see 5 ways to use FileInfo. The Length often can be safely cast to an int.Long
FileInfo: The code creates a new FileInfo—this allows us to get the file size. We use the Length property and a long value.
Next: It calls File.AppendAllText. This is an example call that changes the file's contents.File
Length: We get the size of the file with the FileInfo class. The sizes are in bytes.
Finally: It calculates the difference. We can test the difference between the file sizes to see if the file got bigger or smaller.
C# program that gets file size
static void Main()
// The name of the file.
const string fileName = "test.txt";
// Create new FileInfo object and get the Length.
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
// Change something with the file.
File.AppendAllText(fileName, " More characters.");
// Create another FileInfo object and get the Length.
FileInfo f2 = new FileInfo(fileName);
long s2 = f2.Length;
// Print the length of the file before and after.
Console.WriteLine("Before and after: " + s1.ToString() +
" " + s2.ToString());
// Get the difference between the two sizes.
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
Before and after: 3 20
Size increase: 17
I recommend always wrapping file-handling code in try and catch blocks. Few developers are experts at exception handling. But I speak from experience when I say: wrap IO code with exception handlers.ExceptionTryCatch
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. You can test whether a file is bigger or smaller after processing.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.