Home > Backend Development > C#.Net Tutorial > How to get human-readable file size in bytes abbreviation using C#?

How to get human-readable file size in bytes abbreviation using C#?

WBOY
Release: 2023-09-03 21:57:03
forward
962 people have browsed it

如何使用 C# 获取人类可读的文件大小(以字节缩写为单位)?

To get the directory, C# provides the Directory.GetDirectories method

Directory.GetDirectories returns the name of the subdirectory (including its path) in the specified directory that matches the specified search pattern ), and optionally search subdirectories

To obtain files, C# provides the Directory.GetFiles method

Directory.GetFiles returns the names (including their paths) of all files matching the specified search pattern , and can optionally search subdirectories

In order to obtain 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();
}
Copy after login

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
Copy after login

The above is the detailed content of How to get human-readable file size in bytes abbreviation using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template