फाइल आकार को मानव-पठनीय फॉर्मेट (KB, MB, GB) में बदलने के लिए:
बुनियादी उदाहरण
static void Main(string[] args)
{
string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
long size = new FileInfo(file).Length;
// सरल रूपांतरण (केवल KB)
long sizeKB = size / 1024;
string humanKBSize = $"{sizeKB} KB";
// बेहतर: स्वचालित इकाई चयन
string humanSize = GetHumanReadableSize(size);
Console.WriteLine($"{Path.GetFileName(file)}: {humanSize}");
}
Console.ReadLine();
}
static string GetHumanReadableSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
int order = 0;
double size = bytes;
while (size >= 1024 && order < sizes.Length - 1)
{
order++;
size /= 1024;
}
return $"{size:0.##} {sizes[order]}";
}
आउटपुट
Topdirectory.txt: 22 B
TestFolderMain.txt: 1.5 KB
TestFolderMain1.txt: 10 KB
TestFolderMain2.txt: 2.3 MB
TestFolderSubDirectory.txt: 1.2 GB
उन्नत संस्करण (अधिक सटीक)
public static string FormatFileSize(long bytes, int decimalPlaces = 2)
{
if (bytes == 0) return "0 B";
string[] suffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
int index = (int)Math.Floor(Math.Log(bytes, 1024));
index = Math.Min(index, suffixes.Length - 1);
double size = bytes / Math.Pow(1024, index);
return $"{size:N{decimalPlaces}} {suffixes[index]}";
}
// उपयोग
Console.WriteLine(FormatFileSize(1023)); // 1,023.00 B
Console.WriteLine(FormatFileSize(1024)); // 1.00 KB
Console.WriteLine(FormatFileSize(1536)); // 1.50 KB
Console.WriteLine(FormatFileSize(1048576)); // 1.00 MB
Console.WriteLine(FormatFileSize(1073741824)); // 1.00 GB
एक्सटेंशन मेथड के रूप में
public static class FileInfoExtensions
{
public static string GetHumanReadableSize(this FileInfo fileInfo)
{
return FormatFileSize(fileInfo.Length);
}
public static string FormatFileSize(long bytes, int decimalPlaces = 2)
{
if (bytes == 0) return "0 B";
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int index = Math.Min((int)Math.Floor(Math.Log(bytes, 1024)), suffixes.Length - 1);
double size = bytes / Math.Pow(1024, index);
return $"{size:N{decimalPlaces}} {suffixes[index]}";
}
}
// उपयोग
var info = new FileInfo(@"C:\file.txt");
Console.WriteLine(info.GetHumanReadableSize());
नोट: मूल कोड में बग
मूल उदाहरण में एक बग था - यह KB में आकार की गणना करता था लेकिन फिर उसी KB मान का उपयोग MB और GB की गणना के लिए करता था:
// गलत (मूल कोड)
long size = new FileInfo(file).Length / 1024; // KB में
string humanMBSize = $"{size / 1024} MB"; // KB/1024 = MB ✓
string humanGBSize = $"{size / 1024 / 1024} GB"; // KB/1024/1024 = GB ✗ (यह KB/1048576 है)
सही गणना के लिए मूल बाइट मान का उपयोग करें या ऊपर दिखाए अनुसार उचित रूपांतरण फ़ंक्शन का उपयोग करें।