Chuyển đổi kích thước file từ byte sang KB, MB, GB... để hiển thị thân thiện với người dùng.
Phương pháp đơn giản
static string FormatFileSize(long bytes)
{
string[] units = { "B", "KB", "MB", "GB", "TB", "PB" };
double size = bytes;
int unitIndex = 0;
while (size >= 1024 && unitIndex < units.Length - 1)
{
size /= 1024;
unitIndex++;
}
return $"{size:0.##} {units[unitIndex]}";
}
Ví dụ hoàn chỉnh
using System;
using System.IO;
class Program
{
static void Main()
{
string rootPath = @"C:\TestFolder";
var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
long bytes = new FileInfo(file).Length;
string readable = FormatFileSize(bytes);
Console.WriteLine($"{Path.GetFileName(file)}: {readable}");
}
Console.ReadLine();
}
static string FormatFileSize(long bytes)
{
if (bytes < 0) return "0 B";
string[] units = { "B", "KB", "MB", "GB", "TB" };
int i = 0;
double size = bytes;
while (size >= 1024 && i < units.Length - 1)
{
size /= 1024;
i++;
}
return $"{size:0.##} {units[i]}";
}
}
Kết quả mẫu
config.json: 1.23 KB
image.png: 2.5 MB
video.mp4: 1.2 GB
empty.txt: 0 B
Phiên bản nâng cao (có làm tròn, localization)
static string FormatFileSizeAdvanced(long bytes, string culture = "en-US")
{
if (bytes == 0) return "0 B";
var ci = new System.Globalization.CultureInfo(culture);
string[] units = { "B", "KB", "MB", "GB", "TB" };
int unit = (int)Math.Floor(Math.Log(bytes, 1024));
unit = Math.Min(unit, units.Length - 1);
double size = bytes / Math.Pow(1024, unit);
return size.ToString("0.##", ci) + " " + units[unit];
}
Lưu ý
- 1 KB = 1024 bytes (binary prefix, IEC 60027-2). Một số ngữ cảnh dùng 1000 (SI).
FileInfo.Lengthtrả vềlong(hỗ trợ file > 4GB).- Dùng
Directory.EnumerateFilesthayGetFilescho thư mục lớn để tránh OutOfMemory.