1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
public enum SHFormatFlags : uint
{
SHFMT_ID_DEFAULT = 0xFFFF,
SHFMT_OPT_FULL = 0x1,
SHFMT_OPT_SYSONLY = 0x2,
SHFMT_ERROR = 0xFFFFFFFF,
SHFMT_CANCEL = 0xFFFFFFFE,
SHFMT_NOFORMAT = 0xFFFFFFD,
}
public const uint SHFMT_ERROR = 0xFFFFFFFF;
public const uint SHFMT_CANCEL = 0xFFFFFFFE;
public const uint SHFMT_NOFORMAT = 0xFFFFFFD;
[DllImport("shell32.dll")]
static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID,
uint options);
/// <summary>
/// Permit to check the result of the format call
/// Throw Exception with a detailed message
/// </summary>
/// <param name="shFormatResult"></param>
public static void CheckFormatResult(uint shFormatResult)
{
if (shFormatResult == SHFMT_ERROR)
throw new Exception("An error occurred during the format. This does not indicate that the drive is unformattable.");
if (shFormatResult == SHFMT_CANCEL)
throw new OperationCanceledException("The format was canceled.");
if (shFormatResult == SHFMT_NOFORMAT)
throw new IOException("The drive cannot be formatted.");
//we can exit normally
return;
}
public void formatUSB()
{
uint result = SHFormatDrive(this.Handle,
4, // formatting E:
(uint)SHFormatFlags.SHFMT_ID_DEFAULT,
0); // full format of E:
if (result == (uint)SHFormatFlags.SHFMT_ERROR)
MessageBox.Show("Unable to format the drive");
}
} |