Introduction
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.
Design
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.
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 Next '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 Next 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 MessageBox.show("Drive " & objDisk.Name & " Successfully Defragged.") Else 'Unsuccessful MessageBox.show("Unable To Defrag Drive " & objDisk.Name) End If Next 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.
Conclusion
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!