In many programming scenarios, such as checking file upload limits or monitoring the growth of log files, you often need to retrieve the physical size (number of bytes) of a file.
In C#, using the Length property of the System.IO.FileInfo class is the standard and most efficient way to achieve this.
Implementation: Getting File Size
The following sample code assumes a server log file. It retrieves the file size in “bytes” and then calculates and displays it in easier-to-read units like “Kilobytes (KB)” or “Megabytes (MB)”.
Sample Code
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Path of the file to check
string targetFile = "server_app.log";
// 1. Create a dummy file for testing (Write some text to give it size)
if (!File.Exists(targetFile))
{
using (StreamWriter sw = File.CreateText(targetFile))
{
// Write about 2KB of data
for (int i = 0; i < 50; i++)
{
sw.WriteLine($"[2025-12-26 12:00:{i:00}] Processing request ID:{i * 100} - Status OK");
}
}
}
// 2. Create an instance of the FileInfo class
// Pass the file path to the constructor
FileInfo fileInfo = new FileInfo(targetFile);
// Check if the file exists
if (fileInfo.Exists)
{
// 3. Get the size using the Length property (Unit is bytes)
long bytes = fileInfo.Length;
Console.WriteLine($"File Name : {fileInfo.Name}");
Console.WriteLine($"Base Size : {bytes:#,0} bytes");
// 4. Convert to practical units (KB, MB)
// Generally calculated as 1KB = 1024 Bytes
double kilobytes = bytes / 1024.0;
double megabytes = kilobytes / 1024.0;
// Display up to 2 decimal places
Console.WriteLine($"Size (KB) : {kilobytes:F2} KB");
Console.WriteLine($"Size (MB) : {megabytes:F4} MB");
}
else
{
Console.WriteLine("Error: The specified file was not found.");
}
}
}
Execution Result
File Name : server_app.log
Base Size : 3,250 bytes
Size (KB) : 3.17 KB
Size (MB) : 0.0031 MB
Explanation and Technical Points
1. FileInfo.Length Property
The file size is returned as a long type (64-bit integer). The unit is always Bytes. When you access this property, the metadata is read directly from the OS file system. Since it does not read the entire content of the file, you can retrieve the size of huge video files (e.g., several GB) instantly without consuming memory.
2. Checking for File Existence
Creating a FileInfo instance does not cause an error even if the file does not exist. However, trying to access the .Length property of a non-existent file will throw a FileNotFoundException. Therefore, always check for existence using if (fileInfo.Exists) or include exception handling.
3. Caution: Avoid Reading the Whole File
A common inefficient method used by beginners is to “read the file and measure the length of the array.”
// [Not Recommended] Consumes large amounts of memory and is slow
long size = File.ReadAllBytes("large_movie.mp4").Length;
This loads the entire file content into memory, which can cause the program to crash when handling large files. Always use FileInfo.
