Very recently I required to find the list of folders occupying maximum bytes in my notebook for housekeeping purposes, and was stumped to realise that its no simple task. So here I come with a code snippet, which scans the given drive and writes into an excel file - the folders, and bytes occupied by files in those folders, in KB units. As a pre-requisite, one need to create a directory named “Foldersize” under C: drive and want to place a button (named button1) in winform. Copying the following piece of code and executing will result in creation of an excel file under "c:\foldersize". Open the created excel file, sort the contents in descending order to spot the top culprit folder(s) occupying maximum space in your hard drive. I can guarantee that the code is not performance friendly, however does the required job with ease for me.
It takes circa 30 minutes to scan C: and 15 minutes to examine D:, in my PC.
The following lines scrutinizes D: drive alone, however one can modify the statement in bold with the drive subject to examination. All the best and happy coding.
Imports System.IO
Imports Microsoft.Office.Core
Public fdirsize As Double = 0
Public tmpfdirsize As Double = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim eapp As New Excel.Application
Dim wb As Excel.Workbook = eapp.Workbooks.Add
Dim ws As Excel.Worksheet = wb.Worksheets.Add
Dim irow As Integer = 2
Dim icol As Integer = 2
Dim fname As String
GetDirectorySize("D:\", wb, ws, irow, icol)
fname = "C:\FolderSize\fsize" & Mid(Now, 1, 2) & Mid(Now, 4, 2) & Mid(Now, 7, 4) & ".xls"
wb.SaveAs(fname)
MsgBox("Scan Complete")
wb.Close()
eapp.Quit()
End Sub
Public Function GetDirectorySize(ByVal dirpath As String, ByRef wb As Excel.Workbook, ByRef ws As Excel.Worksheet, ByVal irow As Integer, ByVal icol As Integer) As Double
tmpfdirsize = 0
Dim fsizekb As Double
If System.IO.Directory.Exists(dirpath) = False Then
GetDirectorySize = fdirsize
Exit Function
End If
Try
Dim dirinfo As New System.IO.DirectoryInfo(dirpath)
Dim oFiles As System.IO.FileInfo() = dirinfo.GetFiles()
If CInt(oFiles.Length) > 0 Then
Dim nFileLen As Integer = oFiles.Length
For i As Integer = 0 To nFileLen - 1
fdirsize += oFiles(i).Length
tmpfdirsize += oFiles(i).Length
Next
End If
fsizekb = Math.Round(tmpfdirsize / 1024, 2)
If fsizekb > 0 Then
ws.Cells(irow, icol) = fsizekb
ws.Cells(irow, icol + 1) = "KB"
ws.Cells(irow, icol + 2) = dirpath
irow += 1
End If
Dim oDirectories As System.IO.DirectoryInfo() = dirinfo.GetDirectories()
If dirinfo.GetDirectories.Length > 0 Then
Dim nDirLen As Integer = dirinfo.GetDirectories.Length
For i As Integer = 0 To nDirLen - 1
fdirsize += GetDirectorySize(oDirectories(i).FullName, wb, ws, irow, icol)
irow += 1
Next
End If
Catch ex As Exception
MsgBox(ex.Message & " " & dirpath)
Exit Function
End Try
End Function