DWQA QuestionsCategory: Program. net / C ා what are the methods to convert a file size in bytes to human readable unit size (KB, MB, GB, TB) in application development?
RECTOR asked 2 months ago

In the application development process of. Net / C ා, how can we convert a file size in bytes into human readable unit size (KB, MB, GB, TB) gracefully?
For example, there is currently a file with a size of 7326629 in bytes
How to convert this byte to MB?

3 Answers
RECTOR answered 2 months ago

Use the FileInfo class to convert 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) {
    order++;
    len = len/1024;
}

string result = String.Format("{0:0.##} {1}", len, sizes[order]);

For more details, please refer to:. net / C ා what are the methods to convert a file size in bytes to human readable unit size (KB, MB, GB, TB) in application development?

Zeeko answered 2 months ago

Take a look at this project:https://github.com/Humanizr/H&#8230;

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