How to get a file size in C#

C# Get File Size

The Length property of the FileInfo class returns the file size in bytes. The following code snippet returns the size of a file. Don't forget to import System.IO and System.Text namespaces in your project.

// Get file size  
long size = fi.Length;  
Console.WriteLine("File Size in Bytes: {0}", size);

C# Get File Size Code Example

Here is a complete code example. The following code example uses a FileInfo class to create an object by passing a complete filename. The FileInfo class provides properties to get information about a file, such as a file name, size, full path, extension, and directory name and is read-only when the file was created and last updated.

Note: Make sure to replace the file name with your file name. Also, you can comment //Create a new file code if you already have a file. You may also want to convert the size from bytes to KB, MB, and GB by dividing bytes by 1024, 1024x1024, etc. 

// Full file name   
string fileName = @"C:\Temp\MaheshTXFI.txt";  
FileInfo fi = new FileInfo(fileName);  
// Create a new file   
using (FileStream fs = fi.Create())  
    Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");  
    fs.Write(txt, 0, txt.Length);  
    Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");  
    fs.Write(author, 0, author.Length);  
// Get File Name  
string justFileName = fi.Name;  
Console.WriteLine("File Name: {0}", justFileName);  
// Get file name with full path   
string fullFileName = fi.FullName;  
Console.WriteLine("File Name: {0}", fullFileName);  
// Get file extension   
string extn = fi.Extension;  
Console.WriteLine("File Extension: {0}", extn);  
// Get directory name   
string directoryName = fi.DirectoryName;  
Console.WriteLine("Directory Name: {0}", directoryName);  
// File Exists ?  
bool exists = fi.Exists;  
Console.WriteLine("File Exists: {0}", exists);  
if (fi.Exists)  
    // Get file size  
    long size = fi.Length;  
    Console.WriteLine("File Size in Bytes: {0}", size);  
    // File ReadOnly ?  
    bool IsReadOnly = fi.IsReadOnly;  
    Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);  
    // Creation, last access, and last write time   
    DateTime creationTime = fi.CreationTime;  
    Console.WriteLine("Creation time: {0}", creationTime);  
    DateTime accessTime = fi.LastAccessTime;  
    Console.WriteLine("Last access time: {0}", accessTime);  
    DateTime updatedTime = fi.LastWriteTime;  
    Console.WriteLine("Last write time: {0}", updatedTime);  
Download the complete free book here: FileInfo in C#
You may want to convert the file size from bytes to KB, MB, or GB. Here is a code example: Convert Bytes To KB, MB, GB in C# 

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.