将fileinfo.Length对象测量为kbs

时间:2009-06-29 13:23:37

标签: c# system.io.fileinfo

我有以下代码:

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 个答案:

答案 0 :(得分:17)

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

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个字节,那么可以分别用1 << 10>> 10取代1000/1000,其他人使用1000000和1000000000也是如此。

答案 1 :(得分:7)

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

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"

答案 2 :(得分:3)

请尝试以下行:

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

答案 3 :(得分:1)

稍微重构@lavinio answer

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);
    }
}