4

我有以下代码:

foreach (string p in dirs)
        {
            string path = p;
            string lastAccessTime = File.GetLastAccessTime(path).ToString();
            bool DirFile = File.Exists(path);
            FileInfo fInf = new FileInfo(path);

            DateTime lastWriteTime = File.GetLastWriteTime(p);
            dirFiles.Add(p + "|" + lastAccessTime.ToString() + "|" + DirFile.ToString() + "|" + lastWriteTime.ToString() + "|" + fInf.Length.ToString());


        }

我有一个 fInf.Length.ToString() 并且我想以 kbs 为单位测量输出。关于如何做到这一点的任何想法?例如,我不想获得 2048 作为文件大小,而只想获得 2Kb。

提前感谢您的帮助

4

4 回答 4

19

以下是如何将其分解为千兆字节、兆字节或千字节:

string sLen = fInf.Length.ToString();
if (fInf.Length >= (1 << 30))
    sLen = string.Format("{0}Gb", fInf.Length >> 30);
else
if (fInf.Length >= (1 << 20))
    sLen = string.Format("{0}Mb", fInf.Length >> 20);
else
if (fInf.Length >= (1 << 10))
    sLen = string.Format("{0}Kb", fInf.Length >> 10);

sLen会有你的答案。您可以将它包装在一个函数中,然后传入Length,甚至是FileInfo对象。

如果您想要以 1000 字节为单位而不是“真正的”千字节,则可以分别用and替换1 << 10and ,对于其他使用 1000000 和 1000000000 的人同样如此。>> 101000/1000

于 2009-06-29T13:31:06.770 回答
9

如果您希望长度为(长)整数:

long lengthInK = fInf.Length / 1024;
string forDisplay = lengthInK.ToString("N0") + " KB";    // eg, "48,393 KB"

如果要将长度作为浮点数:

float lengthInK = fInf.Length / 1024f;
string forDisplay = lengthInK.ToString("N2") + " KB";    // eg, "48,393.68 KB"
于 2009-06-29T13:26:15.673 回答
3

试试下面的行:

string sizeInKb = string.Format("{0} kb", fileInfo.Length / 1024);
于 2009-06-29T13:27:43.517 回答
1

重构@lavinio回答一下:

public static string ToFileLengthRepresentation(this long fileLength)
{
    if (fileLength >= 1 << 30)
        return $"{fileLength >> 30}Gb";

    if (fileLength >= 1 << 20)
        return $"{fileLength >> 20}Mb";

    if (fileLength >= 1 << 10)
        return $"{fileLength >> 10}Kb";

    return $"{fileLength}B";
}

[TestFixture]
public class NumberExtensionsTests
{
    [Test]
    [TestCase(1024, "1Kb")]
    [TestCase(2048, "2Kb")]
    [TestCase(2100, "2Kb")]
    [TestCase(700, "700B")]
    [TestCase(1073741824, "1Gb")]
    public void ToFileLengthRepresentation(long amount, string expected)
    {
        amount.ToFileLengthRepresentation().ShouldBe(expected);
    }
}
于 2020-01-19T14:28:23.673 回答