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
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
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.
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.
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.