Filesize to proper display string

Display size of file in the proper maner

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

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.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article