Thursday, January 22, 2004

Get The Filesize Of A Url's Target File In VB.Net

Not too long ago I wrote a program that had the requirement of displaying the size of a file targetted by a URL without actually downloading the file (the filesize was to help the user determined whether or not they wanted to take the time to download the file).

I wrote a little function for Visual Basic.Net to accomplish this, and found it so darn handy that I thought I would post it here for you. Here it is:

     Public Function GetFileSize(ByVal url As String) As Long

Dim request As System.Net.HttpWebRequest
Dim response As System.Net.HttpWebResponse
Dim fileSize As Long

request = System.Net.WebRequest.Create(url)
response = request.GetResponse()
fileSize = response.ContentLength
Return fileSize
Catch ex As Exception
Return -1
End Try

End Function

Some related properties that you can get from an HttpWebResponse object are:

  • CharacterSet - Gets the character set of the response.

  • ContentEncoding - Gets the method used to encode the body of the response.

  • ContentType - Gets the content type of the response.

  • Cookies - Gets or set cookies associated with the response.

  • LastModified - Gets the last date and time the contents of the response was modified.

  • Method - Gets the method used to return the response.

  • ProtocolVersion - Gets the version of the HTTP protocol used in the response.

  • Server - Gets the name of the server that sent the response.

All of the above information can be extracted from the response without actually having to pull down the entire file.