Is there any easy way to create a class that uses IFormatProvider that writes out a user-friendly file-size?
public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
It should result in strings formatted something like "2,5 MB", "3,9 GB", "670 bytes" and so on.
Here is an extension with more precision:
I have taken Eduardo's answer and combined it with a similar example from elsewhere to provide additional options for the formatting.
If you change:
into
the results without additional precision specifier (so just 0:fs instead of 0:fs3) will start to mimic Win32's StrFormatByteSize() by adjusting precision to size.
OK I'm not going to wrap it up as a Format provider but rather than reinventing the wheel there's a Win32 api call to format a size string based on supplied bytes that I've used many times in various applications.
So I imagine you should be able to put together a provider using that as the core conversion code.
Here's a link to the MSDN spec for StrFormatByteSize.
I needed a version that can be localized for different cultures (decimal separator, "byte" translation) and support for all possible binary prefixes (up to Exa). Here is an example that demonstrates how to use it:
And here is the code: