Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 586
Sean Avatar asked Mar 21 '26 08:03

Sean


1 Answers

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);
like image 132
online Thomas Avatar answered Mar 23 '26 21:03

online Thomas