SteveOH

ASP.NET / VB.NET: Get File Size

by on Jul.11, 2008, under Technology

If you want to get the size of a file using (VB), here’s how.  I used this to check if the file is big enough.  If it’s too small (in my application), an existed and the user was told to contact the Administrator.

Dim fileName As String = "myFile.jpg"
 Dim myFileInfo As New FileInfo(.MapPath(fileName))
 Dim fileSizeBytes As UInt32 = myFileInfo.Length
 Response.Write("File: " & fileName & "<br>Bytes (B): " & fileSizeBytes & _ "<br>Kilo Bytes (KB): " & fileSizeBytes / 1024 & "<br>Mega Bytes (MB): " & _ fileSizeBytes / (1024 ^ 2) & "<br>Giga Bytes (GB): " & _ fileSizeBytes / (1024 ^ 3)) 

Note that this only works for files that already exist ‘locally’, not those that are in ‘transport’.  Meaning, you can use this for files on the local server, over the , etc, but you cannot for files pre- or during uploading, only after they’ve been uploaded and saved to the server.

 I hope this saves you some time… or at least a lengthy search on Google.

:, , , ,

2 Comments for this entry

  • Nishant

    i’m trying the below code to get the file size

    filesize = filename1.Length
    Dim filesize1 As String
    If filesize < 1024 Then
    filesize1 = String.Format("{0:N0} B", filesize)
    ElseIf (filesize < 1024 * 1024) Then
    filesize1 = String.Format("{0:N2} KB", filesize / 1024)
    ElseIf (filesize < 1024 * 1024 * 1024) Then
    filesize1 = String.Format("{0:N2} MB", filesize / (1024 ^ 2))
    ElseIf (filesize < 1099511627776) Then
    filesize1 = String.Format("{0:N2} GB", filesize / (1024 ^ 3))
    Else
    filesize1 = String.Format("{0:N2} TB", filesize / (1024 ^ 4))
    End If

    but for a file of 4 GB it returns me 70 B.
    why this is coming pls help

    • Steve O Hernandez

      It looks like you’re hitting the 32-bit wall. Unsigned 32-bit integers can only take on values from 0 to 4,294,967,295. If you’re file is exactly 4 GB (4,294,967,296 bytes) then it is 1 byte over the limit and will either error out or misbehave.

      It looks like your file is 70 bytes over the limit, and thus, you are being returned 70 bytes.

      You would have to either 1) check for 4 GB files and display an error, or 2) run that code on a 64-bit machine. If you do the later, you’d be able to check the size of files up to 2 TB.

      Good luck.

2 Trackbacks / Pingbacks for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!