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.
- static void Main()
- {
- try
- {
- Console.WriteLine("Enter Partition size in GB");
- int partitionSize = Convert.ToInt16(Console.ReadLine());
-
- CreatePartition(partitionSize);
-
- Console.WriteLine("Formate completed");
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- Console.ReadKey();
- }
CreatingPartition
The following is the details of the procedure for this function.
- Get all the drive information of the PC (Including CD drives and network drives)
- Get hard disk drive information (including only hard disk partitions)
- Get the new name for the new partition.
- Check that the partition script file exists, if yes than delete the file.
- Add command text to the script file with a proper parameter.
- Open a command prompt using Process.
- Run the script using a command prompt.
- Delete the script file.
-
-
-
-
-
- private static int CreatePartition(int partitionSizeInGB)
- {
- string sd = string.Empty;
- int result = 0;
-
-
- List < DriveInfo > allDrivesInfo = DriveInfo.GetDrives().Where(x = > x.DriveType != DriveType.Network).OrderBy(c = > c.Name).ToList();
-
-
- char newDriveName = allDrivesInfo.LastOrDefault().Name.FirstOrDefault();
- newDriveName = (Char)(Convert.ToUInt16(newDriveName) + 1);
-
-
- List < DriveInfo > allFixDrives = DriveInfo.GetDrives().Where(c = > c.DriveType == DriveType.Fixed).ToList();
-
- try
- {
- string scriptFilePath = System.IO.Path.GetTempPath() + @
- "\dpScript.txt";
- string driveName = allFixDrives.FirstOrDefault().Name;
-
- if (File.Exists(scriptFilePath))
- {
-
- File.Delete(scriptFilePath);
- }
-
-
- File.AppendAllText(scriptFilePath,
- string.Format(
- "SELECT DISK=0\n" +
- "SELECT VOLUME={0}\n" +
- "SHRINK DESIRED={1} MINIMUM={1}\n" +
- "CREATE PARTITION PRIMARY\n" +
- "ASSIGN LETTER={2}\n" +
- "FORMAT FS=FAT32 QUICK\n" +
- "EXIT", driveName, partitionSizeInGB * 1000, newDriveName));
- int exitcode = 0;
- string resultSen = ExecuteCmdCommand("DiskPart.exe" + " /s " + scriptFilePath, ref exitcode);
- File.Delete(scriptFilePath);
- if (exitcode > 0)
- {
- result = exitcode;
- }
-
- return result;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
ExecuteCmdCommand
We will open a command prompt and run the script in a separate process using C#.
-
-
-
-
-
-
- private static string ExecuteCmdCommand(string Command, ref int ExitCode)
- {
- ProcessStartInfo ProcessInfo;
- Process Process = new Process();
- string myString = string.Empty;
- ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
-
- ProcessInfo.CreateNoWindow = false;
- ProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
- ProcessInfo.UseShellExecute = false;
- ProcessInfo.RedirectStandardOutput = true;
- Process.StartInfo = ProcessInfo;
- Process = Process.Start(ProcessInfo);
- StreamReader myStreamReader = Process.StandardOutput;
- myString = myStreamReader.ReadToEnd();
-
- ExitCode = Process.ExitCode;
- Process.Close();
-
- 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.