Get a descriptive size string for your uploads
In an ASP.NET page, when you've used a System.Web.UI.HtmlControls.HtmlInputFile control in your page - sometimes you want to get the size of the file uploaded. The HttpPostedFile class has a ContentLength property - but the value attainable by using the .ToString() method leaves something to be desired. So, here is a simple little method I wrote to get you a more descriptive string from the ContentLength value - I thought I'd share it here for anyone that wants to do something similar.
C#:
public
static string GetFileSizeStringFromContentLength(int ContentLength){
if(ContentLength > 1048575)
{
return String.Format("{0:0.00 mb}", (Convert.ToDecimal((Convert.ToDouble(ContentLength) / 1024) / 1024))) ;
}
else
{
return String.Format("{0:0.00 kb}", (Convert.ToDecimal(Convert.ToDouble(ContentLength) / 1024))) ;
}
}
VB.NET: Public Function GetFileSizeStringFromContentLength(ByVal ContentLength As Integer) As String
If (ContentLength > 1048575) Then
GetFileSizeStringFromContentLength = String.Format("{0:0.00 mb}", (Convert.ToDecimal((Convert.ToDouble(ContentLength) / 1024) / 1024)))
Else
GetFileSizeStringFromContentLength = String.Format("{0:0.00 kb}", (Convert.ToDecimal(Convert.ToDouble(ContentLength) / 1024)))
End If
End Function
You can adjust the string format to attain more precise size measurements - all I cared to have was something like "230.45 kb" or "2.12 mb" - but you can do whatever you want, of course.