private void LoadDiskDrives() { m_DrivesFound = false; string m_SelectedID = null; BeginInvoke(new Action(() => { if (lstDiskDrive.SelectedItem != null) { m_SelectedID = lstDiskDrive.SelectedItem.ToString(); } lstDiskDrive.DataSource = null; lstDiskDrive.Items.Clear(); lstDiskDrive.Items.Add("(loading...)"); lstDiskDrive.SelectedIndex = 0; this.Refresh(); })); WmiInfo.LoadDiskInfo(); BeginInvoke(new Action(() => { var l = DriveTools.GetRemovableDiskDrives().OrderBy(z => z.ID).ToList(); lstDiskDrive.Items.Clear(); if (l.Count == 0) { lstDiskDrive.Items.Add("(No removable disk drives found)"); lstDiskDrive.SelectedIndex = 0; } else { lstDiskDrive.DataSource = l; m_DrivesFound = true; var o = l.FirstOrDefault(z => z.ID == m_SelectedID); if (o != null) { lstDiskDrive.SelectedItem = o; } else { lstDiskDrive_SelectedIndexChanged(this, EventArgs.Empty); } } lstDiskDrive.Refresh(); })); }
private async void btnFormat_Click(object sender, EventArgs e) { DiskDrive dd = (DiskDrive)lstDiskDrive.SelectedItem; if (dd == null) { MessageBox.Show("Choose valid SD drive first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (MessageBox.Show("All data on SD card will be lost during format. Are you sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No) { return; } SetButtons(false); //if (dd.Volumes.Count() == 0) { var handle = dd.CreateHandle(FileAccess.ReadWrite); var x = IOWrapper.DiskGetDriveLayoutEx(handle); IOWrapper.DiskCreateDiskMBR(handle, 0xa5a5a5); IOWrapper.DiskUpdateProperties(handle); x = IOWrapper.DiskGetDriveLayoutEx(handle); x.PartitionEntry[0].PartitionNumber = 1; x.PartitionEntry[0].StartingOffset = 4 * 512; x.PartitionEntry[0].PartitionLength = (long)dd.GetDriveSize() - x.PartitionEntry[0].StartingOffset; x.PartitionEntry[0].RewritePartition = true; x.PartitionEntry[0].Mbr.PartitionType = (byte)IOWrapper.Partition.FAT32; IOWrapper.DiskSetDriveLayoutEx(handle, x); IOWrapper.DiskUpdateProperties(handle); x = IOWrapper.DiskGetDriveLayoutEx(handle); //IOWrapper.StorageLoadMedia(handle); handle.Close(); var driveID = dd.ID; WmiInfo.LoadDiskInfo(); dd = dd.CreationContext.DiskDrives.FirstOrDefault(z => z.ID == driveID); } this.Text += " (Formatting)"; lblSpeed.Text = "Windows is formatting the drive..."; cts = new CancellationTokenSource(); progress.Value = 0; progress.Maximum = 100; //await Task.Run(() => dd.Format(ProgressHandler, cts.Token)); try { var vol = dd.Volumes.FirstOrDefault(); if (vol != null) { vol.Mount(); await Task.Run(() => dd.Volumes.First().Format("FAT32", true), cts.Token); } } catch (Exception ex) { if (!(ex is OperationCanceledException)) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } cts.Cancel(); } ResetProgress(); FillDriveList(); if (!cts.IsCancellationRequested) { MessageBox.Show("Formatting complete.", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); } cts = null; }