如何将可用字节转换为KB,MB,GB等可用字节? [重复]

问题描述 投票:0回答:1

我正在计算特定文件夹中可用的总字节数,我想将可用的总字节数转换为KB,MB,GB等可用的总字节数。

我可以使用c#中的内置功能吗?

谢谢,

c# asp.net
1个回答
3
投票

我找到了一个非常有信息的博客关于此:

https://askgif.com/blog/143/how-to-convert-given-bytes-in-kb-mb-gb-etc/

如果您正在计算总字节数,那么您可以使用以下函数找出KB,MB,GB,TB等各自的总字节数。

static String BytesToString(long byteCount)
    {
        string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
        if (byteCount == 0)
            return "0" + suf[0];
        long bytes = Math.Abs(byteCount);
        int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
        double num = Math.Round(bytes / Math.Pow(1024, place), 1);
        return (Math.Sign(byteCount) * num).ToString() + suf[place];
    }

希望这会帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.