Geeks With Blogs
Tom Liversidge .net, technology and life

Hi,

I am currently involved in a project that requires information about the size of files to be displayed to a user. Quite a common scenario I'll imagine. There are many examples online of how to convert bytes to megabytes and gigabytes and display a friendly message to the user. All the ones I've seen however, involve creating a method that does this which takes a value as a parameter and returns a string.

My solution for this project was to implement an extension method for variables of type long. (for a good article on extension methods see this post)

public static class MyExtensions
    {
        /// <summary>
        /// Converts the bytes to friendly string.
        /// </summary>
        /// <param name="Bytes">The bytes.</param>
        /// <returns></returns>
        public static string ConvertBytesToFriendlyString(this long Bytes)
        {
            if (Bytes >= 1073741824)
            {
                double displayBytes = Convert.ToDouble(Bytes) / 1024 / 1024 / 1024;
                return String.Format("{0:#0.00}", displayBytes) + " GB";
            }
            else if (Bytes >= 1024)
            {
                double displayBytes = Convert.ToDouble(Bytes) / 1024 / 1024;
                //changed from KB display to MB
                //if it's less than 0.01 then add another decimal point
                if (displayBytes < 0.01)
                {
                    return String.Format("{0:#0.000}", displayBytes) + " MB";
                }
                else
                {
                    return String.Format("{0:#0.00}", displayBytes) + " MB";
                }
            }
            else if (Bytes > 0 & Bytes < 1024)
            {
                return Bytes.ToString() + " Bytes";
            }
            else
            {
                return "0 Bytes";
            }
        }
    } 

You can then call this extension method on any Int64/long (remember to include "using MyExtensions;" in your code behind):

 
long MyLong = 3493524;
string friendlyString = MyLong.ConvertBytesToFriendlyString(); 
// friendlyString = "3.33 MB"

Simple!

Posted on Wednesday, February 24, 2010 4:13 PM .net | Back to top


Comments on this post: Extension method for displaying bytes as megabytes / gigabytes

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © tomliversidge | Powered by: GeeksWithBlogs.net