C#Dot Net Perls

C#
Convert Bytes to Megabytes

by Sam Allen

Problem

Easily convert a figure in bytes to megabytes. This could be because you want to have a more user-friendly number to display to your user. Another requirement is that you may need to get the size of a file. You want to be able to do this accurately and in a way that is easy to maintain.

C# Solution

Here I show a function that converts a number in bytes to megabytes. This helps with user interfaces and communicating to your users a more readable file size. As an added bonus I will show code to convert kilobytes to megabytes.

Implementation details

I will show the code itself next and afterwards will list some important parts about the code. After this section, I will show some calling conventions and also a way to format the display returned from these methods. Right here is the code to convert the numbers.

/// <summary>
/// Convert functions.
/// </summary>
static class ConvertNum
{
    /// <summary>
    /// Convert a number in bytes to a number in megabytes.
    /// </summary>
    /// <param name="bytesIn">The number of bytes.</param>
    /// <returns>The number of megabytes.</returns>
    public static double ConvertBytesToMegabytes(long bytesIn)
    {
        return (bytesIn / 1024f) / 1024f;
    }

    /// <summary>
    /// Convert a number in kilobytes to a number in megabytes.
    /// </summary>
    /// <param name="kilobytesIn">The number of kilobytes.</param>
    /// <returns>The number of megabytes.</returns>
    public static double ConvertKilobytesToMegabytes(long kilobytesIn)
    {
        return kilobytesIn / 1024f;
    }
}

How do I use the above method?

Here I will show how to use the FileInfo object to figure out the length of the file in bytes. Let's say that you have the file "dog.txt". Let's use FileInfo to get some information about it and then convert that to a formatted string in megabytes.

{
    // Get the size of a file.
    FileInfo info = new FileInfo("dog.txt");
    long length = info.Length;

    // Now convert to a string in megabytes.
    string s = ConvertNum.ConvertBytesToMegabytes(info.Length).ToString("0.00");
}

Conclusion

In conclusion, I would like to say that this code is correct, as it matches the results that Google gives. Google knows everything, and if it matches Google, it is correct. Of course, you don't want to use Google to perform such a simple operation.

Downloads

There is a convenient and easy-to-copy version of this code at my open-source code site. The methods there also can convert other types of units.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge