Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I get a human-readable file size in bytes abbreviation using C#?
To get a human-readable file size in bytes with proper abbreviations, C# requires converting raw byte values into appropriate units like KB, MB, GB, or TB. This involves dividing by 1024 (or 1000 depending on your preference) and selecting the most appropriate unit to display.
The key is to create a method that automatically determines the best unit and formats the size accordingly, rather than showing all units simultaneously.
Syntax
To get file size in bytes −
long sizeInBytes = new FileInfo(filePath).Length;
To format the size into human-readable format −
string FormatFileSize(long bytes) {
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int suffixIndex = 0;
double size = bytes;
while (size >= 1024 && suffixIndex < suffixes.Length - 1) {
size /= 1024;
suffixIndex++;
}
return $"{size:0.##} {suffixes[suffixIndex]}";
}
Using a Helper Method for File Size Formatting
The most efficient approach is to create a reusable method that automatically selects the appropriate unit −
using System;
using System.IO;
class Program {
static string FormatFileSize(long bytes) {
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int suffixIndex = 0;
double size = bytes;
while (size >= 1024 && suffixIndex < suffixes.Length - 1) {
size /= 1024;
suffixIndex++;
}
return $"{size:0.##} {suffixes[suffixIndex]}";
}
static void Main(string[] args) {
// Create test files with different sizes
string testFile1 = "small.txt";
string testFile2 = "medium.txt";
File.WriteAllText(testFile1, "Hello World!");
File.WriteAllText(testFile2, new string('A', 2048576)); // ~2MB file
FileInfo file1 = new FileInfo(testFile1);
FileInfo file2 = new FileInfo(testFile2);
Console.WriteLine($"File: {file1.Name}");
Console.WriteLine($"Size: {FormatFileSize(file1.Length)}");
Console.WriteLine();
Console.WriteLine($"File: {file2.Name}");
Console.WriteLine($"Size: {FormatFileSize(file2.Length)}");
// Clean up
File.Delete(testFile1);
File.Delete(testFile2);
}
}
The output of the above code is −
File: small.txt Size: 12 B File: medium.txt Size: 2 MB
Processing Multiple Files with Readable Sizes
Here's how to process multiple files and display their sizes in human-readable format −
using System;
using System.IO;
class Program {
static string FormatFileSize(long bytes) {
if (bytes == 0) return "0 B";
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int suffixIndex = 0;
double size = bytes;
while (size >= 1024 && suffixIndex < suffixes.Length - 1) {
size /= 1024;
suffixIndex++;
}
return $"{size:0.##} {suffixes[suffixIndex]}";
}
static void Main(string[] args) {
// Create test directory and files
string testDir = "TestFiles";
Directory.CreateDirectory(testDir);
File.WriteAllText(Path.Combine(testDir, "tiny.txt"), "Hi");
File.WriteAllText(Path.Combine(testDir, "small.txt"), new string('A', 1024));
File.WriteAllText(Path.Combine(testDir, "large.txt"), new string('B', 1048576));
var files = Directory.GetFiles(testDir, "*.*", SearchOption.AllDirectories);
Console.WriteLine("File Size Report:");
Console.WriteLine("================");
foreach (string file in files) {
FileInfo fileInfo = new FileInfo(file);
Console.WriteLine($"{Path.GetFileName(file)}: {FormatFileSize(fileInfo.Length)}");
}
// Clean up
Directory.Delete(testDir, true);
}
}
The output of the above code is −
File Size Report: ================ large.txt: 1 MB small.txt: 1 KB tiny.txt: 2 B
Using Decimal vs Binary Units
You can choose between binary units (1024) or decimal units (1000) based on your requirements −
using System;
using System.IO;
class Program {
static string FormatFileSizeBinary(long bytes) {
string[] suffixes = { "B", "KiB", "MiB", "GiB", "TiB" };
int suffixIndex = 0;
double size = bytes;
while (size >= 1024 && suffixIndex < suffixes.Length - 1) {
size /= 1024;
suffixIndex++;
}
return $"{size:0.##} {suffixes[suffixIndex]}";
}
static string FormatFileSizeDecimal(long bytes) {
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int suffixIndex = 0;
double size = bytes;
while (size >= 1000 && suffixIndex < suffixes.Length - 1) {
size /= 1000;
suffixIndex++;
}
return $"{size:0.##} {suffixes[suffixIndex]}";
}
static void Main(string[] args) {
long fileSize = 1536000; // 1.5 MB approximately
Console.WriteLine($"File size: {fileSize} bytes");
Console.WriteLine($"Binary units: {FormatFileSizeBinary(fileSize)}");
Console.WriteLine($"Decimal units: {FormatFileSizeDecimal(fileSize)}");
}
}
The output of the above code is −
File size: 1536000 bytes Binary units: 1.46 MiB Decimal units: 1.54 MB
Comparison of Approaches
| Approach | Pros | Cons |
|---|---|---|
| Binary Units (1024) | Traditional computing standard, matches OS displays | Less intuitive for general users |
| Decimal Units (1000) | SI standard, matches storage manufacturer specs | May differ from OS file properties |
| Auto-selecting Unit | Clean output, appropriate precision | Requires helper method implementation |
Conclusion
Converting file sizes to human-readable format in C# involves creating a helper method that automatically selects the appropriate unit (B, KB, MB, GB, TB) and formats the size accordingly. Choose between binary (1024-based) or decimal (1000-based) units depending on your specific requirements and target audience.
