What are the elegant ways to convert a file size in bytes to human-readable unit size (KB,MB,GB,TB) in NET/C-sharp application development

in the. NET/C-sharp application development process, how do we gracefully convert a file size in bytes to a human-readable unit size (KB,MB,GB,TB)?

for example, there is currently a file whose size in bytes is: 7326629
how to convert this byte unit to MB?


use the FileInfo class for the transformation, as follows:

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
    orderPP;
    len = len/1024;
}

string result = String.Format("{0:0.-sharp-sharp} {1}", len, sizes[order]);
For more implementation, see


ide-an-easy-way-convert-bytes-to-kb-mb-gb-etc" rel=" nofollow noreferrer "> https://stackoverflow.com/que.


you can take a look at this project: https://github.com/Humanizr/H.

var fileSize = (10).Kilobytes();

fileSize.Bits      => 81920
fileSize.Bytes     => 10240
fileSize.Kilobytes => 10
fileSize.Megabytes => 0.009765625
fileSize.Gigabytes => 9.53674316e-6
fileSize.Terabytes => 9.31322575e-9
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9115e-1329.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9115e-1329.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?