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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 22, 2021 (image).