Program & Design Tips, tricks, tutorials, and tools on programming & web design

2May/100

Human-readable file size in C#

        static string ReadableFileSize(double size, int unit=0)
        {
            string[] units = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

            while(size >= 1024) {
                size /= 1024;
                ++unit;
            }

            return String.Format("{0:0.#} {1}", size, units[unit]);
        }

I made "bytes" a double so you could pass in fractions, which you might get when calculating download speeds (just add something like "/s" after the output).

Tagged as: , No Comments