protected virtual void OnFormatUSBProgress(FormatUSBProgressEventArgs e) { EventHandler <FormatUSBProgressEventArgs> handler = FormatUSBProgress; if (handler != null) { handler(this, e); } }
public bool FormatUSB(string driveLetter, string fileSystem = "FAT", bool quickFormat = true, int clusterSize = 2048, string label = "", bool enableCompression = false) { //add logic to format Usb drive //verify conditions for the letter format: driveLetter[0] must be letter. driveLetter[1] must be ":" and all the characters mustn't be more than 2 if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0])) { return(false); } /* * DirectoryInfo di = new DirectoryInfo(driveLetter); * foreach (FileInfo file in di.EnumerateFiles()) * { * try { * file.Delete(); * } * catch (UnauthorizedAccessException e) * { * if (e.Source != null) * { * Debug.WriteLine("UnauthorizedAccessException:" + e.Message); * throw; * } * * } * catch (IOException e) * { * if (e.Source != null) * { * Debug.WriteLine("IOExeption: " + e.Message); * throw; * } * } * } * foreach (DirectoryInfo dir in di.EnumerateDirectories()) * { * try * { * dir.Delete(true); * } * catch (UnauthorizedAccessException e) * { * if (e.Source != null) * { * Debug.WriteLine("UnauthorizedAccessException:" + e.Message); * throw; * } * } * catch (IOException e) * { * if (e.Source != null) * { * Debug.WriteLine("IOExeption: " + e.Message); * if (e.HResult != -2147023504) * { * throw; * } * * } * } * } */ ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'"); foreach (ManagementObject vi in searcher.Get()) { try { var completed = false; var watcher = new ManagementOperationObserver(); watcher.Completed += (sender, args) => { Debug.WriteLine("USB format completed " + args.Status); completed = true; OnFormatUSBCompleted(EventArgs.Empty); }; watcher.Progress += (sender, args) => { Debug.WriteLine("USB format in progress " + args.Current); FormatUSBProgressEventArgs eventArgs = new FormatUSBProgressEventArgs(); eventArgs.current = args.Current; OnFormatUSBProgress(eventArgs); }; vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression }); while (!completed) { System.Threading.Thread.Sleep(1000); } } catch (Exception e) { if (e.Source != null) { Debug.WriteLine(e.Message); throw; } } } return(true); }