Format Drive Using C#

Dot Net(.NET) does not have any internal assembly to format the windows drive. So technically using standards programming technique you can not perform format task with
VC++, VB or C# .But there is always an alternative 🙂  .
the format of windows drive in c# can be performed by using DOS COMMAND.

Source code is free to download 😉 .


You can use the same technique for any language C, C++, Java, Ruby etc.
This is the post format windows drive in java uses the same technique as we are going to use here.

The simple dos command to format a drive is

FORMAT G: /Y /FS:NTFS /V:My_LABEL /Q

Where G: is a drive letter for formating.

/Y is used to force the format and bypass the confirmation

Do you really want to format the drive ?
Yes /No

 /FS is used to choose the file system either FAT32 Or NTFS

/V is for labeling the drive after format

/Q is used to perform quick format

These windows format command are executed through this small project . you can send the format parameter trough its UI.

We can execute does command in any language by creatin a batch of these commands and then run the batch file.

Important code are illustrated below :

C sharp code to get the list of all mounted drives :

  public void dinfo()
        {
            try
            {
                DriveInfo[] allDrives = DriveInfo.GetDrives();

                foreach (DriveInfo d in allDrives)
                {
                    if (d.IsReady == true)
                    {
                        string ko = d.VolumeLabel;
                        string dt = System.Convert.ToString(d.DriveType);
                        comboBox1.Items.Add(d.Name.Remove (2));
                    }

                }
            }
            catch { MessageBox.Show("Error Fetching Drive Info", "Error"); }
        }

C# code to create batch file contains windows format code :

StreamWriter w_r;
            w_r = File.CreateText(@"Phoenix.bat");
            w_r.WriteLine("format /y" + type + "/fs:" + filesystem + " " + name);
            w_r.WriteLine(labelofdisk);
            w_r.Close();

C # code to process batch file.

 System.Diagnostics.Process Proc1 = new System.Diagnostics.Process();
            Proc1.StartInfo.FileName = @"Phoenix.bat";
            Proc1.StartInfo.UseShellExecute = false;
            Proc1.StartInfo.CreateNoWindow = true;
            Proc1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Proc1.Start();
            Proc1.WaitForExit();

Complete function

Here the full VC# program i create


Attention : Run As Administrator.

[social_lock]  http://www.4shared.com/file/ntkLU2PK/Format_Drive_Using_C_Sharp.html [/social_lock]

  • martin

    comboBox1.Items.Add(d.Name.Remove (2));
    why is the number 2??