ডিরেক্টরি পাওয়ার জন্য C#-তে Directory.GetDirectories মেথড আছে।
ফাইল পাওয়ার জন্য Directory.GetFiles মেথড আছে।
ফাইল লেঙ্গথ পাওয়ার জন্য Length প্রপার্টি আছে।
উদাহরণ
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 / 1024; // KB
string humanKBSize = string.Format("{0} KB", size);
string humanMBSize = string.Format("{0} MB", size / 1024);
string humanGBSize = string.Format("{0} GB", size / 1024 / 1024);
Console.WriteLine($"KB:{humanKBSize} MB:{humanMBSize} GB:{humanGBSize}");
}
Console.ReadLine();
}
আউটপুট
file C:\Users\Koushik\Desktop\TestFolder\Topdirectory.txt 22 KB 0 MB 0 GB
file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain\TestFolderMain.txt 0 KB 2 MB 0 GB
file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1\TestFolderMain1.txt 0 KB 0 MB 1 GB
file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain1.txt 0 KB 0 MB 1 GB
file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt 0 KB 0 MB 1 GB
file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMainSubDirectory\TestFolderSubDirectory.txt 0 KB 0 MB 1 GB
উন্নত সংস্করণ (সঠিক একক আউটপুট):
static string GetHumanReadableSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
int order = 0;
double len = bytes;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len /= 1024;
}
return $"{len:0.##} {sizes[order]}";
}
// ব্যবহার:
foreach (string file in files)
{
long bytes = new FileInfo(file).Length;
Console.WriteLine($"{Path.GetFileName(file)}: {GetHumanReadableSize(bytes)}");
}
ব্যাখ্যা: মূল উদাহরণে KB, MB, GB আলাদা আলাদা প্রিন্ট করা হয়েছে, যা বিভ্রান্তিকর। উন্নত ভার্সনে একটি ফাংশন দিয়ে সঠিক ইউনিটে ফরম্যাট করা হয়েছে।