Formatting a Drive using C# and WMI
Formatting a drive using C# and WMI
Introduction
Formatting a Drive under Windows is pretty easy using the Explorer context menu or the good old FORMAT in a console window. And although the .NET Framework contains a huge set of useful file manipulating classes and methods, formatting a drive cannot be found in it. Unfortunately, for an automated CF-Card copy station, I needed a way to reinitialize the flash drives by code.
So I went down the technological letter to find a suiting API to do so and as WMI is always a good point to look for hardware stuff, I first began to find something about it in the painful huge clowd of WMI classes and found the answer surprisingly fast.
The Win32_Volume
class, which can be easily queried using the drive letter, holds a Format
method to do the job.
Using a WMI class in .NET via the System.Management
namespace is also an easy task if you know how to do it right. To save a lot of time on searching all things together for all others out there having the same problem, I decided to write this small article.
Using the Code
I did not build a huge class construct, but a single method in the provided sample application to show the trick. I recommend simply to copy the method code into your project, but don't forget to add the System.Management
reference into your project.
The whole bunch of work is done by the FormatVolume
method:
public static bool FormatDrive(string driveLetter,
string fileSystem = "NTFS", bool quickFormat=true,
int clusterSize = 8192, string label = "", bool enableCompression = false )
{
if (driveLetter.Length != 2 || driveLetter[1] != ':'|| !char.IsLetter(driveLetter[0]))
return false;
//query and format given drive
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
vi.InvokeMethod("Format", new object[]
{ fileSystem, quickFormat,clusterSize, label, enableCompression });
}
return true;
}
It uses named parameter, which is the C# 4.0 syntax to prevent all the necessary overloads. For earlier Framework versions, you need to fix this!
I know, it's not programmed very fail-proof, feel free to enhance this in your project
Points of Interest
The Win32_Volume
class is not available under Windows XP and earlier, but I'm sure there is any another class which also provides that functionality, maybe I'll find it and then I'll update the article.
History
- 5th October, 2010: Initial post