WPF File size converter

In CBR, I had to display the file size of the book in the library…in the explorer, in tooltips, on devices…So i had a file size property (as a long) to get it…but my formatting was wrong because somethimes files are very small and the unit is not Mega…

I wrote a LongtoFileSizeConverter combined to my localize engine like below…

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){

if (value is long && targetType == typeof(string)){

long val = (long)value;

if (val > 1048576) // if more than mega

return val / 1048576 + CultureManager.Instance.GetLocalization(“ByCode”, “MEGA”, “(Mb)”);


return val / 1024 + CultureManager.Instance.GetLocalization(“ByCode”, “KILO”, “(Kb)”);


return string.Empty;


Then just bind it to get the right unit display !

<TextBlock Grid.Column=”2″ Grid.Row=”0″ Text=”{Binding Path=Size, Converter={x:Static Converters:LongToFileSizeConverter.Instance}}”…./>

Full code is available on CBR codeplex project : http://wfpbookreader.codeplex.com/


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s