Filesize to proper display string

Display size of file in the proper maner

  • Share

How many times you had to display file size on your web page? Pretty much every time you might have the same issue with recalculating size to KB or MB.

I caught myself doing this for so many times over and over, so finally I decided to write a piece of code for that.

I found a snippet which does some of the stuff (because I do not like to start everything from the scratch over and over), changed it a little bit, optimized (removed string concatenation with "+" operator).

Because I just love extension methods I wrapped this method in an extension methods for long type as file size is returned as a long value in Length property of System.IO.FileInfo class.

        public static string BytesToString(this long byteCount)
        {
            string[] suf = { " B", " KB", " MB", " GB", " TB", " PB", " EB" };
            if (byteCount == 0)
            {
                return string.Concat("0", suf[0]);
            }
            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return string.Concat((Math.Sign(byteCount) * num).ToString(), suf[place]);
        }
    
  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus