繁体   English   中英

将 fileinfo.Length 对象测量为 kbs

[英]Measuring fileinfo.Length objects into kbs

我有以下代码:

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。

预先感谢您的帮助

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

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 字节而不是“真实”千字节,则可以分别用1000/1000替换1 << 10>> 10 ,对于其他使用 1000000 和 1000000000 的类似。

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

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"

试试下面的行:

string sizeInKb = string.Format("{0} kb", fileInfo.Length / 1024);

重构@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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM