简体   繁体   中英

How to programmatically format unallocated space?

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.

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 (eg, NTFS compressed volumes or per-user quotas).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM