Creating a Hard Disk Partition Using C#

Introduction

In this article we will create another partition in a hard disk using C#. We will use Diskpart.exe that is the default provided by Windows. We will create a partition on Windows 7. In one project I got the requirement from the client to create another partition when we install our software. After some search and some basic changes I created a very simple utility that will create a partition.

In this session I am assuming the reader has a basic understanding of C# and how to create a console application in C#. We are not going deeper into the theory. I will just describe some basics of Diskpart and provide a simple example.

DiskPart

DiskPart.exe is a text-mode command interpreter that enables you to manage objects (disks, partitions, or volumes) using scripts or direct input from a command prompt. Before you can use DiskPart.exe commands on a disk, partition, or volume, you must first list and then select the object to give it focus. When an object has focus, any DiskPart.exe commands that you type act on that object. Diskpart differs from many command-line utilities because it does not operate in a single-line mode. Instead, after you start the utility, the commands are read from standard input/output (I/O). You can direct these commands to any disk, partition, or volume. Diskpart comes with Windows by default. For more details of DiskPart please check the following links.

Example

I have created a simple console application. We will create one script file and execute that script file using a command prompt using C#. In this example we will check all Drives available in the PC then based on that we will define a new name for the new partition.

Main

The Main function takes user input for the partition size and calls the CreatePartition() function and shows a success message if the process completes successfully else it will print an error message.

  1. static void Main()   
  2. {  
  3.     try   
  4.     {  
  5.         Console.WriteLine("Enter Partition size in GB");  
  6.         int partitionSize = Convert.ToInt16(Console.ReadLine());  
  7.         //Call to function which will create partition.    
  8.         CreatePartition(partitionSize);  
  9.   
  10.         Console.WriteLine("Formate completed");  
  11.     }   
  12.     catch (Exception ex)  
  13.     {  
  14.         Console.WriteLine(ex.Message);  
  15.     }  
  16.     Console.ReadKey();  
  17. }  
CreatingPartition
 
The following is the details of the procedure for this function.
  1. Get all the drive information of the PC (Including CD drives and network drives)
  2. Get hard disk drive information (including only hard disk partitions)
  3. Get the new name for the new partition.
  4. Check that the partition script file exists, if yes than delete the file.
  5. Add command text to the script file with a proper parameter.
  6. Open a command prompt using Process.
  7. Run the script using a command prompt.
  8. Delete the script file.
  1. /// <summary>    
  2. /// Creates partition on hard disk    
  3. /// </summary>    
  4. /// <param name="partitionSizeInGB">partition size</param>    
  5. /// <returns></returns>    
  6. private static int CreatePartition(int partitionSizeInGB)   
  7. {  
  8.     string sd = string.Empty;  
  9.     int result = 0;  
  10.   
  11.     //Get all drives includes CD drive and network drive.    
  12.     List < DriveInfo > allDrivesInfo = DriveInfo.GetDrives().Where(x = > x.DriveType != DriveType.Network).OrderBy(c = > c.Name).ToList();  
  13.   
  14.     // get new drive name based on existing drives.    
  15.     char newDriveName = allDrivesInfo.LastOrDefault().Name.FirstOrDefault();  
  16.     newDriveName = (Char)(Convert.ToUInt16(newDriveName) + 1);  
  17.   
  18.     // Get Hard drive information    
  19.     List < DriveInfo > allFixDrives = DriveInfo.GetDrives().Where(c = > c.DriveType == DriveType.Fixed).ToList();  
  20.   
  21.     try   
  22.     {  
  23.         string scriptFilePath = System.IO.Path.GetTempPath() + @  
  24.         "\dpScript.txt";  
  25.         string driveName = allFixDrives.FirstOrDefault().Name;  
  26.   
  27.         if (File.Exists(scriptFilePath))   
  28.         {  
  29.             // Note: if the file doesn't exist, no exception is thrown    
  30.             File.Delete(scriptFilePath); // Delete the script, if it exists    
  31.         }  
  32.   
  33.         // Create the script to resize F and make U    
  34.         File.AppendAllText(scriptFilePath,  
  35.         string.Format(  
  36.             "SELECT DISK=0\n" + // Select the first disk drive    
  37.         "SELECT VOLUME={0}\n" + // Select the drive    
  38.         "SHRINK DESIRED={1} MINIMUM={1}\n" + // Shrink to half the original size    
  39.         "CREATE PARTITION PRIMARY\n" + // Make the drive partition    
  40.         "ASSIGN LETTER={2}\n" + // Assign it's letter    
  41.         "FORMAT FS=FAT32 QUICK\n" + // Format it    
  42.         "EXIT", driveName, partitionSizeInGB * 1000, newDriveName)); // And exit    
  43.         int exitcode = 0;  
  44.         string resultSen = ExecuteCmdCommand("DiskPart.exe" + " /s " + scriptFilePath, ref exitcode);  
  45.         File.Delete(scriptFilePath); // Delete the script file    
  46.         if (exitcode > 0)   
  47.         {  
  48.             result = exitcode;  
  49.         }  
  50.   
  51.         return result;  
  52.     }  
  53.     catch (Exception ex)   
  54.     {  
  55.         throw ex;  
  56.     }  
  57. }   
ExecuteCmdCommand

We will open a command prompt and run the script in a separate process using C#.

  1. /// <summary>  
  2. /// cmd command execution method  
  3. /// </summary>  
  4. /// <param name="Command">Command</param>  
  5. /// <param name="Timeout">Timeout period</param>  
  6. /// <returns></returns>  
  7. private static string ExecuteCmdCommand(string Command, ref int ExitCode)  
  8. {  
  9.     ProcessStartInfo ProcessInfo;  
  10.     Process Process = new Process();  
  11.     string myString = string.Empty;  
  12.     ProcessInfo = new ProcessStartInfo("cmd.exe""/C " + Command);  
  13.   
  14.     ProcessInfo.CreateNoWindow = false;  
  15.     ProcessInfo.WindowStyle = ProcessWindowStyle.Normal;  
  16.     ProcessInfo.UseShellExecute = false;  
  17.     ProcessInfo.RedirectStandardOutput = true;  
  18.     Process.StartInfo = ProcessInfo;  
  19.     Process = Process.Start(ProcessInfo);  
  20.     StreamReader myStreamReader = Process.StandardOutput;  
  21.     myString = myStreamReader.ReadToEnd();  
  22.       
  23.     ExitCode = Process.ExitCode;  
  24.     Process.Close();  
  25.       
  26.     return myString;  

I was searching for a proper solution for creating a partition using C# and after a long search I found the following solution from a MSDN forum.
 

Up Next
    Ebook Download
    View all
    Learn
    View all