Example. First we see a static method that converts a number in bytes to megabytes. This helps with user interfaces and communicating to your users a more readable file size.
Detail The methods use the long type. Long here is important because that is the type returned by FileInfo for file sizes.
Example 2. You can use the FileInfo class to figure out the length of the file in bytes. We can then convert the file information to a formatted string in megabytes.
using System;
using System.IO;
class Program
{
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
static void Main()
{
// Get the file information.
FileInfo info = new FileInfo("Anthem.html");
// Now convert to a string in megabytes.
string s = ConvertBytesToMegabytes(info.Length).ToString("0.00");
// Convert bytes to megabytes.
Console.WriteLine("{0} bytes = {1} megabytes",
info.Length,
s);
}
}126593 bytes = 0.12 megabytes
Example 3. We have a number that is in the form of gigabytes, terabytes or megabytes. We want to convert it to another unit scale. This can help with displaying high-level information.
Next We look at a program that actually converts megabytes, gigabytes, and terabytes.
Note The constant float values in the method bodies are processed by the C# compiler before the program ever executes.
So The constant multiplications will cause no performance loss in this program at runtime.
Detail The term gigabyte in the computer industry has been adopted and changed to indicate that it is equal to 1000 megabytes.
Also Scientists have introduced terms such as gibibyte and mebibyte. This fits the standard scientific prefix "kilo," which means 1000.
Summary. We converted between bytes, kilobytes, megabytes and gigabytes. This code is correct—it matches the results that are returned by search engines.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 22, 2021 (image).