เมื่อได้ขนาดไฟล์เป็น Bytes (long) จาก FileInfo.Length มักต้องการแสดงในหน่วยที่อ่านง่าย (KB, MB, GB, TB)
Extension Method แบบครบครัน
public static class FileSizeExtensions
{
private static readonly string[] Units = { "B", "KB", "MB", "GB", "TB", "PB" };
public static string ToHumanReadable(this long bytes, int decimalPlaces = 2)
{
if (bytes == 0) return "0 B";
if (bytes < 0) return "N/A";
int unitIndex = (int)Math.Floor(Math.Log(bytes, 1024));
unitIndex = Math.Min(unitIndex, Units.Length - 1);
double size = bytes / Math.Pow(1024, unitIndex);
return $"{size:N{decimalPlaces}} {Units[unitIndex]}";
}
// Overload สำหรับ FileInfo
public static string ToHumanReadable(this FileInfo fileInfo, int decimalPlaces = 2)
=> fileInfo.Length.ToHumanReadable(decimalPlaces);
}
การใช้งาน
using System;
using System.IO;
static void Main()
{
string rootPath = @"C:\TestFolder";
var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
var info = new FileInfo(file);
Console.WriteLine($"{info.Name}: {info.Length:N0} bytes = {info.ToHumanReadable()}");
}
}
ผลลัพธ์ตัวอย่าง
document.pdf: 1,310,720 bytes = 1.25 MB
image.png: 524,800 bytes = 512.50 KB
notes.txt: 2,150 bytes = 2.10 KB
empty.txt: 0 bytes = 0 B
large.zip: 2,147,483,648 bytes = 2.00 GB
วิธีคำนวณแบบ Manual (ไม่ใช้ Log)
public static string FormatFileSize(long bytes)
{
if (bytes >= 1024L * 1024 * 1024 * 1024)
return $"{(double)bytes / (1024 * 1024 * 1024 * 1024):F2} TB";
if (bytes >= 1024L * 1024 * 1024)
return $"{(double)bytes / (1024 * 1024 * 1024):F2} GB";
if (bytes >= 1024L * 1024)
return $"{(double)bytes / (1024 * 1024):F2} MB";
if (bytes >= 1024L)
return $"{(double)bytes / 1024:F2} KB";
return $"{bytes} B";
}
หมายเหตุเกี่ยวกับ SI vs Binary
| Standard | Base | Unit | ใช้ใน |
|---|---|---|---|
| Binary (IEC 60027) | 1024 | KiB, MiB, GiB | RAM, File Size (Windows) |
| Decimal (SI) | 1000 | KB, MB, GB | Disk Storage (Manufacturers), Network |
โค้ดข้างต้นใช้ Binary (1024) ซึ่งเป็นมาตรฐานใน Windows/File Systems หากต้องการ SI ให้เปลี่ยนเป็น 1000 และ Unit เป็น KB, MB, GB
ใน .NET 6+ มี Built-in?
ยังไม่มี Built-in Method ตรงๆ แต่สามารถใช้ ByteSize Library (NuGet) หรือเขียน Extension เองได้ง่าย