![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I get a human-readable file size in bytes abbreviation using C#?
To get the directories C# provides a method Directory.GetDirectories
Directory.GetDirectories returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.
To get the files, C# provides a method Directory.GetFiles
Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories
To get the file length , C# provides a property Length
Example
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; 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(); }
Output
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
Advertisements