ZetCode

C# ByteSize

last modified October 18, 2026

In this article we show how to use the ByteSize library to work with size values in C#.

The authors define ByteSize as a utility struct that makes byte size representation in code easier by removing the ambiguity of the value being represented.

In computer usage, both metric and binary systems are used to represent multiples of size units. RAM manufacturers use the binary system (1 KB is 1024 bytes), while disk manufacturers use the metric system (1 KB is 1000 bytes). To handle the confusion, a new standard of symbols was developed. It defines the kibi, mebi, gibi, tebi, and pebi prefixes, which represent powers of 2.

The ByteSize library helps us transform between these two systems. ByteSize assumes 1 KB == 1000 B and 1 KiB == 1024 B, to adhere to the IEC and NIST standards. Note that the operating systems differ: Windows reports sizes in powers of 1024 but labels them KB, MB, and GB, while macOS and many Linux tools use powers of 1000.

$ dotnet add package ByteSize

We add the package to the project. The types are in the ByteSizeLib namespace.

Simple example

We want to transform a gigabyte value to a kilobyte value and a bit value to a megabyte value.

Program.cs
using ByteSizeLib;

double n = 1.59;
ByteSize b = ByteSize.FromGigaBytes(n);
Console.WriteLine($"{b} is {b.ToString("#,# KB")}");

long n2 = 12_226_311;
ByteSize b2 = ByteSize.FromBits(n2);
Console.WriteLine($"{b2.ToString("b")} is {b2.ToString("0.#### MB")}");

Console.WriteLine(b.Bytes);
Console.WriteLine(b.MegaBytes);
Console.WriteLine(b.GibiBytes);

We want to express 1.59 GB in KB and 12226311 bits in MB.

ByteSize b = ByteSize.FromGigaBytes(n);

We create a ByteSize value from a GB number with ByteSize.FromGigaBytes. There are similar factory methods for all units, such as FromBytes, FromKiloBytes, FromKibiBytes, and FromBits.

Console.WriteLine($"{b} is {b.ToString("#,# KB")}");

We output the value in KB using the ToString method. The format string combines a number format with a unit symbol. Printing the object without a format picks the unit automatically.

ByteSize b2 = ByteSize.FromBits(n2);
Console.WriteLine($"{b2.ToString("b")} is {b2.ToString("0.#### MB")}");

Likewise, we use ByteSize.FromBits for the bits, and then ToString to represent the value in bits and in MB.

Console.WriteLine(b.Bytes);
Console.WriteLine(b.MegaBytes);
Console.WriteLine(b.GibiBytes);

The properties return the size as a number in the given unit. The value is stored internally as a number of bits, and the properties are plain double or long values.

$ dotnet run
1.59 GB is 1,590,000 KB
12226311 b is 1.5283 MB
1590000000
1590
1.4808028936386108

File size

In the next example, we get the size of a file.

Program.cs
using ByteSizeLib;

File.WriteAllText("sample.txt", new string('x', 1832));

var fi = new FileInfo("sample.txt");
ByteSize bs = ByteSize.FromBytes(fi.Length);

Console.WriteLine(bs);
Console.WriteLine(bs.ToString("KB"));
Console.WriteLine(bs.ToString("KiB"));
Console.WriteLine(bs.ToString("B"));
Console.WriteLine(bs.ToString("b"));
Console.WriteLine(bs.LargestWholeNumberDecimalSymbol);
Console.WriteLine(bs.LargestWholeNumberDecimalValue);

The program writes a file of 1832 bytes and prints its size in multiple symbols.

var fi = new FileInfo("sample.txt");
ByteSize bs = ByteSize.FromBytes(fi.Length);

With FileInfo we get the size of the file in bytes, and create the ByteSize value with ByteSize.FromBytes.

Console.WriteLine(bs.LargestWholeNumberDecimalSymbol);
Console.WriteLine(bs.LargestWholeNumberDecimalValue);

These properties give the symbol and the value of the largest unit for which the size is at least one. The binary variants are LargestWholeNumberBinarySymbol and LargestWholeNumberBinaryValue.

$ dotnet run
1.83 KB
1.83 KB
1.79 KiB
1832 B
14656 b
KB
1.832

The ToString method

The ToString method of ByteSize converts the value to a string. Without a format, the symbol used is the largest unit for which the value is greater than or equal to one. With a format, we can choose the unit and the number of decimals.

Program.cs
using ByteSizeLib;

double n = 1_099_511_627_776;

string[] syms = ["b", "B", "KB", "KiB", "MB", "MiB", "GB", "GiB", "0.######### GB"];

foreach (var sym in syms)
{
    Console.WriteLine($"{sym,-15} {ByteSize.FromBytes(n).ToString(sym)}");
}

Console.WriteLine("--");

// the default format picks the largest unit that gives a value of at least 1
foreach (double bytes in new[] { 0, 512, 1_000, 1_536, 2_500_000, 7_300_000_000 })
{
    Console.WriteLine($"{bytes,14:N0} -> {ByteSize.FromBytes(bytes)}");
}

The program displays one value in different multiples of units, and then shows how the automatic unit selection works.

$ dotnet run
b               8796093022208 b
B               1099511627776 B
KB              1099511627.78 KB
KiB             1073741824 KiB
MB              1099511.63 MB
MiB             1048576 MiB
GB              1099.51 GB
GiB             1024 GiB
0.######### GB  1099.511627776 GB
--
             0 -> 0 B
           512 -> 512 B
         1,000 -> 1 KB
         1,536 -> 1.54 KB
     2,500,000 -> 2.5 MB
 7,300,000,000 -> 7.3 GB

The symbols are case-sensitive in one place: b means bits and B means bytes. The default number format has at most two decimals. A custom number pattern such as 0.######### shows more digits. The decimal prefixes (KB, MB) divide by 1000, and the binary ones (KiB, MiB) by 1024, which is why the same size yields 1099.51 GB and 1024 GiB.

Parsing string values

The Parse and TryParse methods convert the string representation of a size, in the decimal or binary system, to a ByteSize value. The symbols are matched case-insensitively.

Program.cs
using ByteSizeLib;

string[] vals = ["8192 B", "3.6 KB", "1.96 KiB", "3.54kb", "2 gb", "100", "oops"];

foreach (var val in vals)
{
    if (ByteSize.TryParse(val, out ByteSize n))
    {
        Console.WriteLine($"{val,-10} -> {n.Bytes,14} bytes = {n.ToString("KB")}");
    }
    else
    {
        Console.WriteLine($"{val,-10} -> not a valid size");
    }
}

In the example, we parse several strings, convert them to ByteSize, and display them in bytes and in KB.

if (ByteSize.TryParse(val, out ByteSize n))

TryParse returns false for text that is not a size, instead of throwing an exception. A number without a unit, such as "100", is not accepted.

$ dotnet run
8192 B     ->           8192 bytes = 8.19 KB
3.6 KB     ->           3600 bytes = 3.6 KB
1.96 KiB   ->        2007.04 bytes = 2.01 KB
3.54kb     ->           3540 bytes = 3.54 KB
2 gb       ->     2000000000 bytes = 2000000 KB
100        -> not a valid size
oops       -> not a valid size

Note that "1.96 KiB" is 2007.04 bytes; the value is not rounded to whole bytes internally.

Arithmetic and comparison

The ByteSize values can be added, subtracted, compared, and sorted, and the units are converted automatically.

Program.cs
using ByteSizeLib;

var a = ByteSize.FromMegaBytes(1.5);
var b = ByteSize.FromKiloBytes(300);

Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a.Add(b).ToString("KB"));
Console.WriteLine(a > b);
Console.WriteLine(a == ByteSize.FromKiloBytes(1500));
Console.WriteLine(a.CompareTo(b));

var sizes = new[] { a, b, ByteSize.FromGigaBytes(2) };
Console.WriteLine(sizes.Max());
Console.WriteLine(sizes.Order().First());

// ByteSize has no Sum overload, so we add up the bytes
var total = ByteSize.FromBytes(sizes.Sum(s => s.Bytes));
Console.WriteLine(total);

The program adds a megabyte value and a kilobyte value, compares them, and finds the largest value in an array.

Console.WriteLine(a + b);
Console.WriteLine(a - b);

The operators produce new values: 1.5 MB plus 300 KB is 1.8 MB. The same can be done with the Add and Subtract methods, and there are helpers such as AddGigaBytes.

Console.WriteLine(a == ByteSize.FromKiloBytes(1500));

Values in different units are equal if they represent the same number of bits.

Console.WriteLine(sizes.Max());
Console.WriteLine(sizes.Order().First());

The struct implements IComparable, so LINQ's Max and sorting work out of the box. There is no Sum overload for ByteSize, so we add up the byte counts and create a new value.

$ dotnet run
1.8 MB
1.2 MB
1800 KB
True
True
1
2 GB
300 KB
2 GB

The sum in the last line is 2 GB because 1.5 MB and 300 KB are small compared to 2 GB and the default format rounds to two decimals.

Sizes of files in a directory

A typical use of the library is reporting file sizes in a readable form.

Program.cs
using ByteSizeLib;

Directory.CreateDirectory("files/sub");
File.WriteAllText("files/a.txt", new string('a', 1500));
File.WriteAllText("files/b.txt", new string('b', 20_000));
File.WriteAllText("files/sub/c.txt", new string('c', 3_000_000));

var dir = new DirectoryInfo("files");

foreach (var file in dir.EnumerateFiles("*", SearchOption.AllDirectories).OrderByDescending(f => f.Length))
{
    Console.WriteLine($"{file.Name,-8} {ByteSize.FromBytes(file.Length),12}");
}

var total = ByteSize.FromBytes(dir.EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length));
Console.WriteLine($"{"total",-8} {total,12}");

// the same data in the binary system
Console.WriteLine($"{"total",-8} {total.ToBinaryString(),12}");

The program creates three files, lists them from the largest, and prints the total in the decimal and in the binary system.

Console.WriteLine($"{file.Name,-8} {ByteSize.FromBytes(file.Length),12}");

Interpolated strings call ToString on the value, and the alignment component right-aligns the text in a column. The format specifier after a colon would be passed to the same method.

Console.WriteLine($"{"total",-8} {total.ToBinaryString(),12}");

The ToBinaryString method always uses the binary units, so the same total is shown as 2.88 MiB instead of 3.02 MB.

$ dotnet run
c.txt            3 MB
b.txt           20 KB
a.txt          1.5 KB
total         3.02 MB
total        2.88 MiB

Do not confuse the library with Humanizer, which has its own byte size type; see the Humanizer tutorial for the other text-making helpers.

Source

ByteSize Github page

In this article we have worked with the ByteSize library.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.