views:

832

answers:

3

Hello,

I’m looking for a code snippet that would programmatically format unallocated space on a given drive.

I’m ideally looking for .net code (VB.NET C#) or C++.

Many thanks

+1  A: 

The best option seems to be to use WMI. In particular, you'll want to look into the Format method of the Win32_Volume class.

You could instead use the SHFormatDrive function of the Win32 API. This may be the simpler option (especially in C++), though I'm not sure how the functionality compares with the WMI method. Edit: As M. Jahedbozorgan points out, this seems to open the Explorer shell dialog to format the drive.

A third option is to run the command-line format.exe from code (and then read from the stdout stream), but this clearly isn't a very nice solution.

Other suggestions are given in this thread on MSDN forums.

Noldorin
Windows XP and earlier: Win32_Volume class is not available.SHFormatDrive opens the Shell's Format dialog.
M. Jahedbozorgan
Yeah, you seem to be right about SHFormatDrive - well spotted. Are you sure about Win32_Volume and WinXP however?
Noldorin
M. Jahedbozorgan is right - the Win32_Volume documentation on MSDN states that the class s not available for xp and earlier
roo
A: 

It looks like Windows only provides a method to format an entire volume, not just the unallocated space.

So, if I understand your question right, you could create a partition in the remaining space of the drive, then format that new partition.

You will want to use PInvoke and WMI's Win32_Volume.

Jeremy Sena
+1  A: 

Create a file that fills up the entire drive, then write random data to it, then flush it, then close it.

The first step is probably the hardest to do reliably across multiple configurations (e.g., NTFS compressed volumes or per-user quotas).

Or use "cipher /w" from the command line.

MSN