Defragging Disks with VB.NET


I am very curious. It is both a blessing and a curse. Sometimes however, like today it is a big surprise. When getting the idea for this article, I thought it would be a lot of work. Technically, it can be, but with the use of Windows Method Instrumentation (WMI ), it shouldn't be, because we don't have to reinvent the wheel. Today we will learn how to quickly defrag your hard disks.

Our Project

With today's project we will learn very quick ways to defragment our harddrives.


Open Visual Studio and start a new VB.NET Windows Forms application. Name it anything descriptive. Design your form to resemble Figure 1. Obviously, you can name the objects as you please, but keep in mind that my names for the objects may be different than yours.

Our Design
Figure 1 - Our Design

Add the next Namespace:

Imports System.IO 'File Input / Output

This allows us to do file manipulation.

Add the following 2 Modular variables:

    Private lstDrives As New List(Of String) 'List of Drives

	Private arrDrives As String() 'Array of Drives

lstDrives will hold all the drives present on the system, and arrDrives will host the result of some string manipulation, which ultimately provides the current drive string, for example: C:\

Add the Form_Load event:

	Private Sub frmDefrag_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For Each diDrive As DriveInfo In DriveInfo.GetDrives 'Get all Hard Drives Connected To PC
			If diDrive.DriveType = DriveType.Fixed Then 'Is it a HD?

				If diDrive.VolumeLabel <> String.Empty Then 'If Drive Has A "Name"

					'Add To ListBox
					lstDefrag.Items.Add(String.Format("{0} ( {1} )", diDrive.Name, diDrive.VolumeLabel))

				Else 'No Name
					'Show NO NAME Instead Of Empty String
					lstDefrag.Items.Add(String.Format("{0} ( NO NAME )", diDrive.Name))

				End If
            End If


		'Enable Defrag Button If Current User Is Logged In As Admin
        btnDefrag.Enabled = My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator)

    End Sub

We make use of a For Each loop to loop through all the Fixed Drives (hard drives). We then determine each drive's given name and add it to our listbox. The bottom line is quite interesting! It checks to see if the current user is the Admin. If he / she is not, the button will remain disabled.

Add the next two event procedures:

    Private Sub btnDefrag_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefrag.Click

        bwDefrag.RunWorkerAsync(0.0) 'Run Defrag Task In Background

        Me.WindowState = FormWindowState.Minimized 'Minimize Form

    End Sub

    Private Sub bwDefrag_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwDefrag.DoWork

        For Each strDrive As String In lstDrives 'Loop Through Drives In ListBox

            Dim pDefragProc As New Process 'Create a New Process

            Dim psiDefrag As New ProcessStartInfo("defrag.exe") 'Start defrag.exe

            psiDefrag.Arguments = strDrive 'Supply Drive Name

            pDefragProc.StartInfo = psiDefrag

            pDefragProc.Start() 'Start
            pDefragProc.WaitForExit() 'Wait Until Completion or Exit


	End Sub

The click event starts the background worker named bwDefrag and minimizes the form. The second sub does the actual work. This is simply starting the defrag.exe process on the computer and waiting for the process to finish. Luckily it is on a separate thread, as your program might have frozen if it was on the same thread.

Now, some of you may be surprised that I have taken this route. Well the reason behind this is to show you how quick the WMI method will be. Although it will take some time, it will be quicker than the built in Windows Defragger.

Add the next subs:

	Private sub FormulateDriveString
		arrDrives = lstDefrag.SelectedItem.Split("\") 'Split At \
		lstDrives.Add(arrDrives(0)) 'First Item Is Drive String

	End sub
	Private Sub lstDefrag_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstDefrag.SelectedIndexChanged
			FormulateDriveString 'Format String Correctly

	End Sub

Here, we obtain the selected item from our listbox. Then, with the help of the FormulateDriveString sub, we obtain the physical drive name, for example:  C:\. This we will use with the WMI button's click event, which we can add now:

	Private Sub btnDefragWMI_Click( sender As Object,  e As EventArgs) Handles btnDefragWMI.Click
		Dim objWMI As Object 'Create WMI Object

		Dim objDisk As Object 'Disk Object

		Dim colDisks As Object 'Disks Collection

		Dim objResult As Object 'Able To Defragment / Not

		'Get All Disk On System
		objWMI = GetObject("winmgmts:\\" & Environment.MachineName & "\root\cimv2")

		colDisks = objWMI.ExecQuery("Select * from Win32_Volume Where Name = '" & arrDrives(0) & "'")

		For Each objDisk In colDisks 'Loop Through All Disks

			objResult = objDisk.Defrag() 'Try To Defrag

			If objResult = 0 Then 'Successful"Drive " & objDisk.Name & " Successfully Defragged.")

			Else 'Unsuccessful"Unable To Defrag Drive " & objDisk.Name)

			End If


	End Sub

We create a WMI query to obtain all the hard-disks connected to the pc or inside the pc; we then use the Defrag method to defrag them.


Well, there you have it! Sometimes a thing looks complicated from the outside and turns out to be easy, and vice versa. As a developer I never get tired of pleasant surprises. Until next time, cheers!

Related Articles



  • Need Help Sir

    Posted by Jaymar on 02/12/2015 05:41pm

    Sir.the application is not working please help me...or kindly send me a working project..thank you sir..

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Moving from an on-premises environment to Office 365 does not remove the need to plan for disruptions or reduce the business risk requirements for protecting email services. If anything, some risks increase with a move to the cloud. Read how to ease the transition every business faces if considering or already migrating to cloud email. This white paper discusses: Setting expectations when migrating to Office 365 Understanding the implications of relying solely on Exchange Online security Necessary archiving …

  • Anthony Christie, the Chief Marketing Officer for Level Communications, is responsible for customer experience, worldwide marketing and product management. In this informative asset, he shares his insights into why a private network connection to cloud-bases applications is the right decision for your enterprise. Download now to find out more.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date