How to get folder size in .NET

Posted by NosaLee in .NET Programming, Common Programming on 24-04-2012. Tags: ,

Author: Nosa Lee
Original Address: http://www.seeksunslowly.com/dot-net-get-folder-size
To reprint this article, please indicate the source, thank you.
_____________________________________

The .NET built-in assemblies (I use .NET 3.5) do not provide a way to get the folder/directory size directly.
If use the preset .NET assemblies to get it, you need to traverse all files under a folder and its sub folders, it is inefficient and cumbersome.

If you have worked in VB6 programming previously, you should know each version of Windows has a COM – Windows Script Host Object Model (wshom.ocx), the Folder object of this component can get folder size directly.

Now I provide a example in VB 2008 to explain how to do (get folder size):

1. Create a new Windows Form Application and open its properties page, choose References, click Add… -> Reference… drop-down button like this:
.NET Get Folder Size Picture 1

2. Choose Windows Script Host Object Model in the COM tab page on the popup window and click <OK> like below:
.NET Get Folder Size Picture 2

3. At this time, the references list will add a new item: Windows Script Host Object Model, please select this reference and press <F4>, double-click Path property, copy the full path of this wrapper assembly, like this:
.NET Get Folder Size Picture 3

4. Usually, we do not operate COM directly, so please delete this COM reference (click <Remove> button). We will use the related wrapper .NET assembly, click Add… -> Reference… drop-down button again, paste above full path of this wrapper assembly to [File name] field on the Browse tab page, and then click <OK>, like below:
.NET Get Folder Size Picture 4

5. Good, at this time you can already use the wrapper assembly – Interop.IWshRuntimeLibrary to get folder size directly, the code as below:

1
2
3
4
5
6
7
Public Class Form1
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Dim f As IWshRuntimeLibrary.Folder
      f = New IWshRuntimeLibrary.FileSystemObject().GetFolder("h:\test")
      MsgBox(f.Path & " " & f.Size & " Bytes") ' Please note the unit is Bytes, you may need to do conversion according to your requirement.
   End Sub
End Class

6. Run this project, you will see the effect like below:
.NET Get Folder Size Picture 5

Note: this way is not only appropriate for .NET, you can also apply it to other Windows programming languages that do not provide the folder size query interface, please refer to this article to to your works.

Post a comment