0

I am using the following in C# to get the length of a file

long length = new System.IO.FileInfo(path).Length;

How can I nicely parse the file into same as Windows displays it:

2.92 MB (3,072,000 bytes)

user829174
  • 6,132
  • 24
  • 75
  • 125
  • I don't think there's a built-in. But you can 1)find the order of magnitude, 2)divide, 3)format to two decimal places, and 4)stick the prefix onto the unit. Aaaaaaand...there's a duplicate. Of course. – lc. Sep 07 '15 at 12:27
  • `Console.WriteLine("{0:##0.00} ({1:#,###} bytes)", volume / (1024.0 * 1024.0), volume);` – Mark Shevchenko Sep 07 '15 at 12:31
  • A quick way is to use the [Humanizer](https://github.com/MehdiK/Humanizer) NuGet package: `fileSize.Bytes().ToString("#.##")` will give the desired result. – Martin Liversage Sep 07 '15 at 12:32
  • FileInfo fi = new FileInfo(path); float byteLength = (fi.Length / 1024f) / 1024f; String outputString = byteLength.ToString("0.##") + " MB (" + fi.Length + " bytes)"; – Bgl86 Sep 07 '15 at 12:40

0 Answers0