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)”);

else

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/