简体   繁体   中英

Measuring fileinfo.Length objects into kbs

I have the following code:

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


        }

I have a fInf.Length.ToString() and i'd like to measure the output in terms of kbs. Any ideas on how do accomplish this? For example, instead of getting 2048 as a File Size, i'd like to just get 2Kb.

Thanks in advance for help

Here's how to get it broken down in gigabytes, megabytes or kilobytes:

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 will have your answer. You could wrap it in a function and just pass in the Length , or even the FileInfo object.

If instead of 'real' kilobytes, you wanted it in terms of 1000's of bytes, you could replace 1 << 10 and >> 10 with 1000 and /1000 respectively, and similarly for the others using 1000000 and 1000000000.

If you want the length as a (long) integer:

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

If you want the length as a floating point:

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

Refactoring @lavinio answer a bit:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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