EaterOfCode
EaterOfCode

Reputation: 2222

how to parse size of file to string

How do I parse the size of a file from like 1024 to 1kb? once I created a function for it which was like 30 lines long full of if's. is there a more 'elegant' way to do it? and what do I need to use? 1kb = 1000b or 1kb = 1024b?

Upvotes: 1

Views: 2608

Answers (5)

Black Light
Black Light

Reputation: 2404

Not that you need lots of (vaguely) similar ways but, seeing as no-one has as yet suggested it (and for a little old fashioned fun), you could do this...

// Note: StrFormatByteSize truncates as opposed to rounds (so, 1.998 becomes 1.99, not 2.00)
[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);

private static String FormatBytes(Int64 bytes)
{
     StringBuilder sb = new StringBuilder(10);
     StrFormatByteSize(bytes, sb, 10);
     return sb.ToString();
}

...or my version of the answers already offered...

private static String FormatBytes(Int64 bytes)
{
     const Int64 KB = 1024,
                 MB = KB * 1024,
                 GB = MB * 1024,
                 TB = GB * 1024L,
                 PB = TB * 1024L,
                 EB = PB * 1024L;
    if (bytes < KB) return bytes.ToString("N0") + " Bytes";
    if (bytes < MB) return Decimal.Divide(bytes, KB).ToString("N") + " KB";
    if (bytes < GB) return Decimal.Divide(bytes, MB).ToString("N") + " MB";
    if (bytes < TB) return Decimal.Divide(bytes, GB).ToString("N") + " GB";
    if (bytes < PB) return Decimal.Divide(bytes, TB).ToString("N") + " TB";
    if (bytes < EB) return Decimal.Divide(bytes, PB).ToString("N") + " PB";
    return Decimal.Divide(bytes, EB).ToString("N") + " EB";
}

Upvotes: 3

fero
fero

Reputation: 6183

How about this:

public string FormatSize(long size)
{
    double result = size;

    var sizes = new string[] { "", "K", "M", "G", "T", "P", "E" };

    int i = 0;
    while (result > 1000 && i < sizes.Length)
    {
        result /= 1000; // or 1024 if you want
        i++;
    }

    // EDIT: Optimized decimal places

    string format = "{0:0.00} {1}B"; // default: 2 decimals

    switch (sizes[i])
    {
        case "":
            format = "{0} B"; // no decimals for bytes
            break;
        case "K":
            format = "{0:0.0} KB"; // 1 decimal for KB
            break;
    }

    // /EDIT

    return string.Format(format, result, sizes[i]);
}

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272287

This solution doesn't look unreasonable. It's a little long, but it does cater for exa/petabytes!

C# Human-Readable File Size Function

// Returns the human-readable file size for an arbitrary, 64-bit file size
//  The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
public static string GetSizeReadable(long i)
{
    string sign = (i < 0 ? "-" : "");
    double readable = (i < 0 ? -i : i);
    string suffix;
    if (i >= 0x1000000000000000) // Exabyte
    {
        suffix = "EB";
        readable = (double)(i >> 50);
    }
    else if (i >= 0x4000000000000) // Petabyte
    {
        suffix = "PB";
        readable = (double)(i >> 40);
    }
    else if (i >= 0x10000000000) // Terabyte
    {
        suffix = "TB";
        readable = (double)(i >> 30);
    }
    else if (i >= 0x40000000) // Gigabyte
    {
        suffix = "GB";
        readable = (double)(i >> 20);
    }
    else if (i >= 0x100000) // Megabyte
    {
        suffix = "MB";
        readable = (double)(i >> 10);
    }
    else if (i >= 0x400) // Kilobyte
    {
        suffix = "KB";
        readable = (double)i;
    }
    else
    {
        return i.ToString(sign + "0 B"); // Byte
    }
    readable = readable / 1024;

    return sign + readable.ToString("0.### ") + suffix;
}

Sample Usage

It is recommended to put the above function in a helper or utility class as a public static method.

// EXAMPLE OUTPUT
GetSizeReadable(1023); // 1023 B
GetSizeReadable(1024); // 1 KB
GetSizeReadable(1025); // 1.001 KB

// Example of getting a file size and converting it to a readable value
string fileName = "abc.txt";
long fileSize = new System.IO.FileInfo(fileName).Length;
string sizeReadable = GetSizeReadable(fileSize);

Upvotes: 7

Simon Whitehead
Simon Whitehead

Reputation: 65079

Perhaps something like this?

public string FileSizeAsString(long lengthOfFile)
{
    string[] sizes = { "bytes", "KB", "MB", "GB" };
    int j = 0;

    while (lengthOfFile > 1024 && j < sizes.Length)
    {
        lengthOfFile = lengthOfFile / 1024;
        j++;
    }
    return (lengthOfFile + " " + sizes[j]);
}

Usage:

Console.WriteLine(FileSizeAsString(new FileInfo(@"C:\\your_file_here.ext").Length));

You can expand the string array sizes as you see fit and it will continue calculating.

Upvotes: 6

Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13582

int fileSize = 10485258;//size of your file
string size = fileSize >= 1024*1024 ?  
    (fileSize / 1024 / 1024).ToString()+"MB" :
    (fileSize >= 1024 ? (fileSize / 1024).ToString() + "KB" : fileSize.ToString() + "B");
MessageBox.Show(size);

Upvotes: 0

Related Questions