Get the size of a Sub Folder/Sub Directory excluding the Parent Folder - vb.net

i have a listview that shows folders and files, and i can display the size of the files and subfolders, but how do i do it with subfolders only not including the parent/root folder.
EDIT
like, if Folder1's size is 10 MB and it has a SubFolder with 20 MB size with a total of 30 MB, it should only get the size of the SubFolder which is 20 MB when displaying the contents of the Folder1 in a ListView.
Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
Dim dis As DirectoryInfo() = d.GetDirectories()
Dim di As DirectoryInfo
For Each di In dis
Size += DirSize(di)
Next di
Return Size
End Function
my listview code:
Sub lv1items()
ListView1.Items.Clear()
Dim fPath As String = Form2.TextBox1.Text
Dim di = New DirectoryInfo(fPath)
' store imagelist index for known/found file types
Dim exts As New Dictionary(Of String, Int32)
If di.Exists = False Then
MessageBox.Show("Destination path" & " " & Form2.TextBox1.Text & " is not found.", "Directory Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form2.Show()
Else
Dim img As Image
Dim lvi As ListViewItem
For Each d In di.EnumerateDirectories("*.*", SearchOption.TopDirectoryOnly)
lvi = New ListViewItem(d.Name)
lvi.SubItems.Add(DirSize(di).ToString("0.00") & " MB")
lvi.SubItems.Add(d.CreationTime.Date)
ListView1.Items.Add(lvi)
img = NativeMethods.GetShellIcon(d.FullName)
ImageList1.Images.Add(img)
lvi.ImageIndex = ImageList1.Images.Count - 1
Next
End Sub
it returns a 0 size folder, but it has a file inside.
a little help please?

You can use this function:
Public Function GetDirectorySize(path As String) As Long
Dim files() As String = Directory.GetFiles(path, "*", SearchOption.AllDirectories)
Dim size As Long = 0
For Each file As String In files
Dim info As New FileInfo(file)
size += info.Length
Next
Return size
End Function
Note that this checks the size of every file in the folder and its subdirectories. Thus it is guaranteed to return the correct size.
Proof that it works:
Root:
SubFolder:
Total Size = (1483 + 25315) * 1024 = 274411152 bytes.
Program Output:
27440016 bytes ≈ 274411152 bytes.
Note: The difference exists because Windows Explorer rounds off some bytes to display the KB. If you view the properties of each file and add up then you will get the same size from both Explorer and the function.

Related

Copy directories and files with ProgressBar

Trying to create a console application to copy directories from the source to the destination and either the progress bar does nothing while files are copied...
My.Computer.FileSystem.CopyDirectory(source, destination)
For i = 1 To 100
Console.Write(String.Format("Copy progress: {0}%" & vbCr, i))
Threading.Thread.Sleep(100)
Next
or the ProgressBar says "Copy Progress 1%" the entire time it's copying...
For i = 1 To 100
Console.Write(String.Format("Copy progress: {0}%" & vbCr, i))
My.Computer.FileSystem.CopyDirectory(source, destination)
Threading.Thread.Sleep(100)
Next
Wondering what I am doing wrong because I am obviously putting the My.Computer line in the wrong spot!
A simple solution, using Linq Select to copy the file list returned by DirectoryInfo.GetFiles()
Pass the sample method an array of Source Directories and a Destination Directory.
The progress (0-100%) is printed to the Output window, and a ProgressBar gives a visual feedback of the copy status for each Source Path.
This method will return the list of all files copied.
Dim sourcePath As String() = New String() {"[SourcePath1]", "[SourcePath2]", "[SourcePath3]"}
Dim destinationPath As String = "[DestinationPath]"
Dim filesCopied As List(Of String) = CopyDirectoryWithProgress(sourcePath, destinationPath)
Console.ReadLine()
Private Function CopyDirectoryWithProgress(sourcePath As String(), destPath As String) As List(Of String)
Dim allFilesCopied As List(Of String) = New List(Of String)
Dim progressBarPassSymbol As Char = ChrW(&H25A0)
Dim progressBarEmptySymbol As String = New String(ChrW(&H2014), 30)
For Each sPath As String In sourcePath
Dim fileInfo As New DirectoryInfo(sPath).GetFiles()
Dim numberOfFiles As Integer = fileInfo.Length - 1
Dim progressBarPass As Double = (30 / numberOfFiles)
Dim increment As Double = 100 / numberOfFiles
Directory.CreateDirectory(destPath)
Console.CursorLeft = 0
Console.Write("Copy progress: ")
Console.CursorLeft = 20
Console.Write(progressBarEmptySymbol)
allFilesCopied.AddRange(fileInfo.
Select(Function(f, i)
File.Copy(Path.Combine(sPath, f.Name), Path.Combine(destPath, f.Name), True)
Console.CursorLeft = 15
Console.Write("{0:g}% " &
New String(progressBarPassSymbol, CInt((i + 1) * progressBarPass)),
CInt((i + 1) * increment))
Return f.FullName
End Function))
Console.WriteLine()
Next
Return allFilesCopied
End Function
For an interesting method to perform this task with a much faster file enumerator, see this CodeProject article: A Faster Directory Enumerator
You can invoke the Windows built-in progress bar when copying using the UIOption.AllDialogs:
My.Computer.FileSystem.CopyFile("C:\text.txt", "C:\my_folder\text.txt", FileIO.UIOption.AllDialogs, FileIO.UICancelOption.DoNothing)

Getting duplicate entries in treeView and Extra Space in listView Item image

I am making a test program to let the user select a folder from a tree view which will show the drives and folders (when expanded) and the files that are present in the selected folder will be displayed in the listview.
The problem i am facing with the listview is that, there is a extra space added before the file icon of every file.
And i am also getting duplicate folder entries when expanded in the treeview.
the icon size of imageListListView is 24x24
Public Class FolderTreeStructure
Private Sub FolderTreeStructre_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'add drive list in treeview
Dim drives() As String = System.IO.Directory.GetLogicalDrives()
For Each drive In drives
TreeView1.Nodes.Add(drive)
Next
'add folder present in each drives
Dim folders() As String
Dim j As Integer = 0
For i As Integer = 0 To TreeView1.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(TreeView1.Nodes.Item(i).Text)
For Each folder In folders
TreeView1.Nodes.Item(i).Nodes.Add(folder)
TreeView1.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
End Sub
Private Sub TreeView1_AfterExpand(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterExpand
Me.Cursor = Cursors.WaitCursor
Dim folders() As String
Dim j As Integer = 0
TreeView1.BeginUpdate()
For i As Integer = 0 To e.Node.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(e.Node.Nodes.Item(i).Text)
For Each folder In folders
e.Node.Nodes.Item(i).Nodes.Add(folder)
e.Node.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
TreeView1.EndUpdate()
Me.Cursor = Cursors.Default
End Sub
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
addFolderItems(e.Node.Text)
End Sub
Public Sub addFolderItems(ByVal path As String)
Try
ListView1.Items.Clear()
Dim files() As String = IO.Directory.GetFiles(path)
Dim fileCount As Integer = files.Length
Dim fileInfo As IO.FileInfo
Dim i As Integer = 0
Dim Items = ListView1.Items
'different file sizes
Dim fileSize As Long
Dim kb As Double
Dim mb As Double
Dim gb As Double
'for extracting file type description
Dim Clskey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
Dim ExtKey As Microsoft.Win32.RegistryKey
Dim Appkey2 As Microsoft.Win32.RegistryKey
Dim AppDesc As String
'to hold file icon
Dim iconForFile As Icon = SystemIcons.WinLogo
ListView1.BeginUpdate()
For Each file In files
Try
fileInfo = New IO.FileInfo(file)
'adds item number
Items.Add(Items.Count + 1)
'adds file name
Items.Item(i).SubItems.Add(fileInfo.Name)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (ImageListListView.Images.ContainsKey(fileInfo.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
ImageListListView.Images.Add(fileInfo.Extension, iconForFile)
End If
Items.Item(i).ImageKey = fileInfo.Extension
'adds file size
fileSize = fileInfo.Length
If fileSize > 1024 Then
kb = fileSize / 1024
If kb > 1024 Then
mb = kb / 1024
If mb > 1024 Then
gb = mb / 1024
Items.Item(i).SubItems.Add(Format(gb, "0.00") & " GB")
Else
Items.Item(i).SubItems.Add(Format(mb, "0.00") & " MB")
End If
Else
Items.Item(i).SubItems.Add(Format(kb, "0.00") & " KB")
End If
Else
Items.Item(i).SubItems.Add(fileSize.ToString & " bytes")
End If
'adds file extension without .
If fileInfo.Extension.Length > 0 Then
Items.Item(i).SubItems.Add(fileInfo.Extension.Substring(1))
Else
Items.Item(i).SubItems.Add(fileInfo.Extension)
End If
'adds date modified
Items.Item(i).SubItems.Add(fileInfo.LastWriteTime.ToString)
'extract file type description from registry
ExtKey = Clskey.OpenSubKey(fileInfo.Extension, False)
If ExtKey IsNot Nothing Then 'Occurs nullreff when extension not found
AppDesc = ExtKey.GetValue("", "")
Appkey2 = Clskey.OpenSubKey(AppDesc)
Items.Item(i).SubItems.Add(Appkey2.GetValue("", ""))
End If
i += 1
Catch
Continue For
End Try
Next
ListView1.EndUpdate()
Catch e As Exception
MsgBox(e.ToString)
End Try
End Sub
End Class
Link for image
http://i.imgur.com/GLS0ZiO.png

Visual Basic Error Generating Folder SHA256 Hash

I want to generate a single SHA256 hash of all the files in a folder in visual basic. I have tried the following code but it generates individual hashes of all files inside the folder, but not a single hash. Can anybody please help.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim directory As String
If TextBox2.Text.Length < 1 Then
Dim fdb As New FolderBrowserDialog
Dim dr As DialogResult = fdb.ShowDialog()
If (dr = DialogResult.OK) Then
directory = fdb.SelectedPath
Else
MsgBox("No directory selected")
Return
End If
Else
directory = TextBox2.Text
End If
Try
' Create a DirectoryInfo object representing the specified directory.
Dim dir As New DirectoryInfo(directory)
' Get the FileInfo objects for every file in the directory.
Dim files As FileInfo() = dir.GetFiles()
' Initialize a SHA256 hash object.
Dim mySHA256 As SHA256 = SHA256Managed.Create()
Dim hashValue() As Byte
' Compute and print the hash values for each file in directory.
Dim fInfo As FileInfo
For Each fInfo In files
' Create a fileStream for the file.
Dim fileStream As FileStream = fInfo.Open(FileMode.Open)
' Be sure it's positioned to the beginning of the stream.
fileStream.Position = 0
' Compute the hash of the fileStream.
hashValue = mySHA256.ComputeHash(fileStream)
' Write the name of the file to the Console.
MsgBox(fInfo.Name + ": ")
' Write the hash value to the Console.
PrintByteArray(hashValue)
' Close the file.
fileStream.Close()
Next fInfo
Return
Catch DExc As DirectoryNotFoundException
MsgBox("Error: The directory specified could not be found.")
Catch IOExc As IOException
MsgBox("Error: A file in the directory could not be accessed.")
End Try
End Sub
Public Function PrintByteArray(ByVal array() As Byte)
Dim i As Integer
For i = 0 To array.Length - 1
Label3.Text = (String.Format("{0:X2}", array(i)))
If i Mod 4 = 3 Then
Label3.Text = (" ")
End If
Next i
Return Label3.Text
End Function 'PrintByteArray
You can combine the hashes with XOR to give one 256-bit hash (32 bytes). Because XOR is associative (A XOR B = B XOR A), it does not matter in which order you XOR the file hashes together. You will have to XOR the individual bytes of each hash: Most efficient way to xor byte array in vb.net.

Why is each String being written to a different file?

I am trying to generate a size-based list of files. The current size being passed is 10 MB worth of file-names per text file. Instead of it counting to 10 MB and then incrementing the version letter, it is writing each file-name to its own individual file. This is strange as each file is ~150 kb, but I cannot figure out why it is reporting total as > number every time the code loops.
Private Function GenerateListsForSize(source As String, destination As String, name As String, number As Integer)
Dim files As ArrayList = New ArrayList
Dim total As Integer
Dim version As Char = "A"
Dim path As String
Dim counter As Integer = 0
Dim passTexts As ArrayList = New ArrayList
Dim infoReader As System.IO.FileInfo
For Each foundFile As String In My.Computer.FileSystem.GetFiles(source)
files.Add(foundFile)
Next
If files.Count > 1 Then 'If files exist in dir, count them and get how many lists
path = destination & "\" & name & version & ".txt"
Dim fs As FileStream = File.Create(path) 'creates the first text file
fs.Close()
passTexts.Add(path)
For Each foundfile As String In files
Using sw As StreamWriter = New StreamWriter(path)
Console.WriteLine(foundfile)
sw.WriteLine(foundfile)
End Using
infoReader = My.Computer.FileSystem.GetFileInfo(foundfile)
total = total + infoReader.Length
If total >= number Then 'If max file size is reached
version = Chr(Asc(version) + 1) 'Increments Version
path = destination & "\" & name & version & ".txt" 'Corrects path
fs = File.Create(path) 'creates the new text file with updated path
fs.Close()
passTexts.Add(path)
total = 0 'resets total
End If
Next
End If
Return passTexts
End Function
Every time through the loop, you open the file (using the StreamWriter) which overwrites the previous contents. Your file will only ever have one filename inside it. Instead of opening and writing every time through the loop, only write the file when you have accumulated all the filenames. I removed the calls to File.Create as they aren't necessary. The StreamWriter will create the file if it doesn't exist. And I changed the ArrayList's to List(Of String) since they're easier to work with. Also, be sure to turn Option Strict On. This code has not been tested, but it should get my point across. I hope I haven't misunderstood what you were trying to do.
Private Function GenerateListsForSize(source As String, destination As String, name As String, number As Integer) As List(Of String)
Dim files As New List(Of String)()
Dim filenamesToWrite As New List(Of String)()
Dim total As Integer
Dim version As Char = "A"
Dim filename As String
Dim counter As Integer = 0
Dim passTexts As New List(Of String)()
Dim infoReader As System.IO.FileInfo
files.AddRange(My.Computer.FileSystem.GetFiles(source))
If files.Count > 1 Then 'If files exist in dir, count them and get how many lists
'Path.Combine is preferable to concatenating strings.
filename = Path.Combine(destination, String.Format("{0}{1}.txt", name, version))
passTexts.Add(filename)
For Each foundfile As String In files
filenamesToWrite.Add(foundfile)
infoReader = My.Computer.FileSystem.GetFileInfo(foundfile)
total = total + infoReader.Length
If total >= number Then 'If max file size is reached
'Only write when the list is complete for this batch.
Using sw As StreamWriter = New StreamWriter(filename)
For Each fname As String In filenamesToWrite
Console.WriteLine(foundfile)
sw.WriteLine(foundfile)
Next
End Using
version = Chr(Asc(version) + 1) 'Increments Version
filename = Path.Combine(destination, String.Format("{0}{1}.txt", name, version)) 'corrects path
passTexts.Add(filename) 'IS THIS A DUPLICATE????
total = 0 'resets total
filenamesToWrite.Clear() 'clear the list of file names to write
End If
Next
End If
Return passTexts
End Function

What’s the best way to calculate the size of a directory in VB .NET?

I need to calculate the directory size in VB .Net
I know the following 2 methods
Method 1: from MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
' The following example calculates the size of a directory
' and its subdirectories, if any, and displays the total size
' in bytes.
Imports System
Imports System.IO
Public Class ShowDirSize
Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
' Add file sizes.
Dim fis As FileInfo() = d.GetFiles()
Dim fi As FileInfo
For Each fi In fis
Size += fi.Length
Next fi
' Add subdirectory sizes.
Dim dis As DirectoryInfo() = d.GetDirectories()
Dim di As DirectoryInfo
For Each di In dis
Size += DirSize(di)
Next di
Return Size
End Function 'DirSize
Public Shared Sub Main(ByVal args() As String)
If args.Length <> 1 Then
Console.WriteLine("You must provide a directory argument at the command line.")
Else
Dim d As New DirectoryInfo(args(0))
Dim dsize As Long = DirSize(d)
Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, dsize)
End If
End Sub 'Main
End Class 'ShowDirSize
Method 2: from What's the best way to calculate the size of a directory in .NET?
Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder, _
FileIO.SearchOption.SearchAllSubDirectories) _
Select New System.IO.FileInfo(strFile).Length).Sum()
Both these methods work fine. However they take lot of time to calculate the directory size if there are lot of sub-folders. e.g i have a directory with 150,000 sub-folders. The above methods took around 1 hr 30 mins to calculate the size of the directory. However, if I check the size from windows it takes less than a minute.
Please suggest better and faster ways to calculate the size of the directory.
Though this answer is talking about Python, the concept applies here as well.
Windows Explorer uses system API calls FindFirstFile and FindNextFile recursively to pull file information, and then can access the file sizes very quickly through the data that's passed back via a struct, WIN32_FIND_DATA: http://msdn.microsoft.com/en-us/library/aa365740(v=VS.85).aspx.
My suggestion would be to implement these API calls using P/Invoke, and I believe you will experience significant performance gains.
Doing the work in parallel should make it faster, at least on multi-core machines. Try this C# code. You will have to translate for VB.NET.
private static long DirSize(string sourceDir, bool recurse)
{
long size = 0;
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
Interlocked.Add(ref size, (new FileInfo(fileName)).Length);
}
if (recurse)
{
string[] subdirEntries = Directory.GetDirectories(sourceDir);
Parallel.For<long>(0, subdirEntries.Length, () => 0, (i, loop, subtotal) =>
{
if ((File.GetAttributes(subdirEntries[i]) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
subtotal += DirSize(subdirEntries[i], true);
return subtotal;
}
return 0;
},
(x) => Interlocked.Add(ref size, x)
);
}
return size;
}
This is a short and sweet code snippet that will get the job done. You just need to reset the counter before you call the function
Public Class Form1
Dim TotalSize As Long = 0
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
TotalSize = 0 'Reset the counter
Dim TheSize As Long = GetDirSize("C:\Test")
MsgBox(FormatNumber(TheSize, 0) & " Bytes" & vbCr & _
FormatNumber(TheSize / 1024, 1) & " Kilobytes" & vbCr & _
FormatNumber(TheSize / 1024 / 1024, 1) & " Megabytes" & vbCr & _
FormatNumber(TheSize / 1024 / 1024 / 1024, 1) & " Gigabytes")
End Sub
Public Function GetDirSize(RootFolder As String) As Long
Dim FolderInfo = New IO.DirectoryInfo(RootFolder)
For Each File In FolderInfo.GetFiles : TotalSize += File.Length
Next
For Each SubFolderInfo In FolderInfo.GetDirectories : GetDirSize(SubFolderInfo.FullName)
Next
Return TotalSize
End Function
End Class
Big thanks #Jamie for Code and #Mathiasfk for translating to VB.net. I use it for my own Backup program which in default setting just backup the whole profile folder, it's a code which finally also is able to understand junction points and read more or less correct size. It's at least okay for Backup. :-)
I just had to put code within Try so it doesn't stop for folders it doesn't have access to, if you also could have such problem just use this (doesn't handle the error just skip it, you can add if important for you):
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Public Function GetFolderSize(ByVal path As String, Optional recurse As Boolean = True) As Long
Dim totalSize As Long = 0
Try
Dim files() As String = Directory.GetFiles(path)
Parallel.For(0, files.Length,
Sub(index As Integer)
Dim fi As New FileInfo(files(index))
Dim size As Long = fi.Length
Interlocked.Add(totalSize, size)
End Sub)
Catch ex As Exception
End Try
Try
If recurse Then
Dim subDirs() As String = Directory.GetDirectories(path)
Dim subTotal As Long = 0
Parallel.For(0, subDirs.Length,
Function(index As Integer)
If (File.GetAttributes(subDirs(index)) And FileAttributes.ReparsePoint) <> FileAttributes.ReparsePoint Then
Interlocked.Add(subTotal, GetFolderSize(subDirs(index), True))
Return subTotal
End If
Return 0
End Function)
Interlocked.Add(totalSize, subTotal)
End If
Catch ex As Exception
End Try
Return totalSize
End Function
Here this as short as I can get it.
It will display the size of the selected in a message box.
You're going to need a FolderBrowserDialog in the form for this to work.
Class Form1
Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
Else : End
End If
Dim dInfo As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
Dim sizeOfDir As Long = DirectorySize(dInfo, True)
MsgBox("Showing Directory size of " & FolderBrowserDialog1.SelectedPath _
& vbNewLine & "Directory size in Bytes : " & "Bytes " & sizeOfDir _
& vbNewLine & "Directory size in KB : " & "KB " & Math.Round(sizeOfDir / 1024, 3) _
& vbNewLine & "Directory size in MB : " & "MB " & Math.Round(sizeOfDir / (1024 * 1024), 3) _
& vbNewLine & "Directory size in GB : " & "GB " & Math.Round(sizeOfDir / (1024 * 1024 * 1024), 3))
Catch ex As Exception
End Try
End Sub
Private Function DirectorySize(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubDir As Boolean) As Long
Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
If includeSubDir Then totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
Return totalSize
End Function
End Class
VB Code based on Jamie's answer:
Imports System.Threading
Imports System.IO
Public Function GetDirectorySize(ByVal path As String, Optional recurse As Boolean = False) As Long
Dim totalSize As Long = 0
Dim files() As String = Directory.GetFiles(path)
Parallel.For(0, files.Length,
Sub(index As Integer)
Dim fi As New FileInfo(files(index))
Dim size As Long = fi.Length
Interlocked.Add(totalSize, size)
End Sub)
If recurse Then
Dim subDirs() As String = Directory.GetDirectories(path)
Dim subTotal As Long = 0
Parallel.For(0, subDirs.Length,
Function(index As Integer)
If (File.GetAttributes(subDirs(index)) And FileAttributes.ReparsePoint) <> FileAttributes.ReparsePoint Then
Interlocked.Add(subTotal, GetDirectorySize(subDirs(index), True))
Return subTotal
End If
Return 0
End Function)
Interlocked.Add(totalSize, subTotal)
End If
Return totalSize
End Function
Try this to get total size in GB
Dim fso = CreateObject("Scripting.FileSystemObject")
Dim profile = fso.GetFolder("folder_path")
MsgBox(profile.Size / 1073741824)
heres what i think is the best way to do it .
Imports System.IO
Public Class FolderSizeCalculator
Public Shared Function GetFolderSize(ByVal folderPath As String) As Long
Dim size As Long = 0
Try
Dim files As String() = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories)
For Each file As String In files
Dim fileInfo As New FileInfo(file)
size += fileInfo.Length
Next
Catch ex As Exception
' Handle any exceptions that may occur
End Try
Return size
End Function
End Class
You can call the GetFolderSize() method and pass in the path of the folder you want to calculate the size of, and it will return the size in bytes.
You can use it like this:
Dim folderSize As Long = FolderSizeCalculator.GetFolderSize("C:\MyFolder")
Console.WriteLine("Folder size: " & folderSize & " bytes")
..Please note that this method will fail if the user running the application doesn't have permission to read the folder or subfolders, you can handle that by using try catch block