Hibri Marzook Musings on technology and systems thinking

HOWTO Get the size of a file as a formatted string

Quick and dirty function to return the size of a file in a properly formatted string in KB, MB or GB. There has to be an easier way than this …..

 

private const double KByte = 1024;
    private const double MByte = KByte * 1024;
    private const double GByte = MByte * 1024;

public static string GetFileSizeString(int bytes) {
        if ((bytes / GByte) < 1) {
            if ((bytes / MByte) < 1) {
                if ((bytes / KByte) < 1) {
                    return String.Format("{0} B", bytes);
                }
                else {
                    return String.Format("{0} KB", Math.Round((bytes / KByte), 2));
                }
            }
            else {
                return String.Format("{0} MB", Math.Round((bytes / MByte), 2));
            }
        }
        else {
            return String.Format("{0} GB", Math.Round((bytes / GByte), 2));
        }
        
    }

By Hibri Marzook

Discuss this post with me on @hibri