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



  • There are no comments yet. Be the first to comment!

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

Top White Papers and Webcasts

  • Mobile is introducing sweeping changes throughout your workplace. As a senior stakeholder driving mobile initiatives in your organization, you may be lost in a sea of technologies and claims from vendors promising rapid delivery of applications to your employees, customers, and partners. To help explain some of the topics you will need to be aware of, and to separate the must-haves from the nice-to-haves, this reference guide can help you with applying a mobile strategy in the context of application …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds