Formatting USB Drives programmatically

10,030

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);
Share:
10,030
Sean
Author by

Sean

I'm a Website Coordinator and C# developer throughout the day. However, at night, my heart belongs to Video Games and, of course, my partner. In my spare time, aside from the above, you'll always find me on StackOverflow or Arqade. I've been in the gaming industry (mainly on Xbox360 platform) for well over 12 years and I will try to give 100% in every piece of advice I provide. I am now in the process of moving away from console gameplay & becoming more focused on PC platform gaming.

Updated on June 08, 2022

Comments

  • Sean
    Sean almost 2 years

    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.