Sean
Sean

Reputation: 442

Formatting USB Drives programmatically

I am developing an application in C# so whereby, if the user confirms a messagebox to formatting a USB drive, selected from a combobox list, the drive will be formatted.

I haven't got an idea how to approach this, however - I have the following code:

 public static bool FormatDrive(string driveLetter,
    string fileSystem = "FAT", bool quickFormat = false,
    int clusterSize = 4096, string label = "", bool enableCompression = false)
    {
        if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
            return false;

        //query and format given drive         
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
         (@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
        foreach (ManagementObject vi in searcher.Get())
        {
            vi.InvokeMethod("Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
        }

        return true;
    } 

I'm not really sure how this works. Is this the correct way to approach formatting USB Drives? If not, could someone point me in the right direction?

I have tried looking at the Win32_Volume class but, again, I don't really understand how it works. This question would suggest using the CreateFile function. I have also looked at this website.

Any tips of pushing me into the right direction, would be much appreciated.

Upvotes: 3

Views: 13249

Answers (2)

Răzvan Bălan
Răzvan Bălan

Reputation: 33

I have also tried this and worked:

public bool FormatUSB(string driveLetter, string fileSystem = "FAT32", bool quickFormat = true,
                                   int clusterSize = 4096, string label = "USB_0000", 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;

        //query and format given drive 
        //best option is to use ManagementObjectSearcher

        var files = Directory.GetFiles(driveLetter);
        var directories = Directory.GetDirectories(driveLetter);

        foreach (var item in files)
        {
            try
            {
                File.Delete(item);
            }
            catch (UnauthorizedAccessException) { }
            catch (IOException) { }
        }

        foreach (var item in directories)
        {
            try
            {
                Directory.Delete(item);
            }
            catch (UnauthorizedAccessException) { }
            catch (IOException) { }
        }

        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) =>
                {
                    Console.WriteLine("USB format completed " + args.Status);
                    completed = true;
                };
                watcher.Progress += (sender, args) =>
                {
                    Console.WriteLine("USB format in progress " + args.Current);
                };

                vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });

                while (!completed) { System.Threading.Thread.Sleep(1000); }


            }
            catch
            {

            }
        }
        return true;
    }
    #endregion

Maybe it will help.

Upvotes: 1

online Thomas
online Thomas

Reputation: 9381

Well maybe I have another method:

    public static bool FormatDrive_CommandLine(char driveLetter, string label = "", string fileSystem = "NTFS", bool quickFormat = true, bool enableCompression = false, int? clusterSize = null)
    {
        #region args check

        if (!Char.IsLetter(driveLetter) ||
            !IsFileSystemValid(fileSystem))
        {
            return false;
        }

        #endregion
        bool success = false;
        string drive = driveLetter + ":";
        try
        {
            var di                     = new DriveInfo(drive);
            var psi                    = new ProcessStartInfo();
            psi.FileName               = "format.com";
            psi.CreateNoWindow         = true; //if you want to hide the window
            psi.WorkingDirectory       = Environment.SystemDirectory;
            psi.Arguments              = "/FS:" + fileSystem +
                                         " /Y" +
                                         " /V:" + label +
                                         (quickFormat ? " /Q" : "") +
                                         ((fileSystem == "NTFS" && enableCompression) ? " /C" : "") +
                                         (clusterSize.HasValue ? " /A:" + clusterSize.Value : "") +
                                         " " + drive;
            psi.UseShellExecute        = false;
            psi.CreateNoWindow         = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput  = true;
            var formatProcess          = Process.Start(psi);
            var swStandardInput        = formatProcess.StandardInput;
            swStandardInput.WriteLine();
            formatProcess.WaitForExit();
            success = true;
        }
        catch (Exception) { }
        return success;
    }

First I wrote the code myself, now found a perfect method on http://www.metasharp.net/index.php/Format_a_Hard_Drive_in_Csharp

Answers to questions in comment:

Remove the /q if you don't want it to quick format

/x parameter forces the selected volume to dismount, if needed.

source: http://ccm.net/faq/9524-windows-how-to-format-a-usb-key-from-the-command-prompt

psi.CreateNoWindow = true;

Hides the terminal so your application looks smooth. My advice is showing it while debugging.

What you want to call is if the drive is F:/ for example:

FormatDrive_CommandLine('F', "formattedDrive", "FAT32", false, false);

Upvotes: 1

Related Questions