TheDeveloperBlog.com


C# FileInfo Length, Get File Size

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, both before and after. We easily get the file size.

FileInfo
Based on:

.NET 4.5


Example. As an example, FileInfo is useful if your program modifies files, and you want to see how many bytes have been added or removed. This is useful for compression or just data analysis.

Here: We see five ways to use FileInfo. The Length is returned as a long, but it often can be safely cast to an int.

Long
C# program that gets file size

using System;
using System.IO;

class Program
{
    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());
    }
}

Output

Before and after: 3 20
Size increase: 17

It creates a new 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.AppendAllText

Next: 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.

Tip: This code is useful for running image compression programs, maintaining log files on your server with ASP.NET, or for displaying.

PNG Optimization

Exceptions. 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.