Thursday, 3 January 2013

Get File Size in B/KB/MB/GB/TB in VB.NET

 Get File Size in B/KB/MB/GB/TB in VB.NET

Getting File size  for a directory files in a human readable format(KB,MB,GB,TB etc.,) using VB.NET recursion.
Same thing can be applied to drive information(i.e:available space, free space and tota

Dim sizeArry() As String =  New String() {"Byes", "KB", "MB", "GB"}
'recursion function
Private Function Get_Size_in_KB_MB_GB(sizebytes As ULong, index As Integer) As [String]

    If sizebytes < 1000 Then
        Return sizebytes + sizeArry(index)

        Return Get_Size_in_KB_MB_GB(sizebytes / 1024, System.Threading.Interlocked.Increment(index))
    End If

End Function
Get Files from a directory and find each file size.

Private Sub GetFileSize(dir As [String])
    For Each szFile As [String] In System.IO.Directory.GetFiles(dir)
            Dim fi As New FileInfo(szFile)

            Console.WriteLine("fileName=" + fi.Name + "Size=" + Get_Size_in_KB_MB_GB(CULng(fi.Length), 0))
        Catch generatedExceptionName As Exception
        End Try
End Sub