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 which 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 research 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.

What is 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.

What is the Main function?

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

static void Main()
{
    try
    {
        Console.WriteLine("Enter Partition size in GB");
        int partitionSize = Convert.ToInt16(Console.ReadLine());
        // Call to function which will create partition.
        CreatePartition(partitionSize);
        Console.WriteLine("Format completed");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadKey();
}

How to create a partition using Diskpart?

The following are 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, then 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.
/// <summary>
/// Creates a partition on the hard disk.
/// </summary>
/// <param name="partitionSizeInGB">Partition size in gigabytes</param>
/// <returns>Exit code indicating the success or failure of the operation</returns>
private static int CreatePartition(int partitionSizeInGB)
{
    string sd = string.Empty;
    int result = 0;
    // Get all drives excluding CD drives and network drives.
    List<DriveInfo> allDrivesInfo = DriveInfo.GetDrives().Where(x => x.DriveType != DriveType.Network).OrderBy(c => c.Name).ToList();
    // Get a new drive name based on existing drives.
    char newDriveName = allDrivesInfo.LastOrDefault()?.Name.FirstOrDefault() ?? 'A';
    newDriveName = (char)(Convert.ToUInt16(newDriveName) + 1);
    // Get information about fixed drives.
    List<DriveInfo> allFixedDrives = DriveInfo.GetDrives().Where(c => c.DriveType == DriveType.Fixed).ToList();

    try
    {
        string scriptFilePath = System.IO.Path.GetTempPath() + @"\dpScript.txt";
        string driveName = allFixedDrives.FirstOrDefault()?.Name;
        if (File.Exists(scriptFilePath))
        {
            File.Delete(scriptFilePath); // Delete the script if it exists.
        }
        // Create the script to resize and format the partition.
        File.AppendAllText(scriptFilePath,
            string.Format(
                "SELECT DISK=0\n" +       // Select the first disk drive.
                "SELECT VOLUME={0}\n" +   // Select the drive.
                "SHRINK DESIRED={1} MINIMUM={1}\n" + // Shrink to half the original size.
                "CREATE PARTITION PRIMARY\n" +       // Make the drive partition.
                "ASSIGN LETTER={2}\n" +             // Assign its letter.
                "FORMAT FS=FAT32 QUICK\n" +         // Format it.
                "EXIT",
                driveName, partitionSizeInGB * 1000, newDriveName)); // Exit.
        int exitCode = 0;
        string resultStr = ExecuteCmdCommand("DiskPart.exe" + " /s " + scriptFilePath, ref exitCode);
        File.Delete(scriptFilePath); // Delete the script file.
        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#.

/// <summary>
/// Executes a command using the cmd.exe process.
/// </summary>
/// <param name="command">The command to execute</param>
/// <param name="exitCode">The exit code of the executed command</param>
/// <returns>The output of the command</returns>
private static string ExecuteCmdCommand(string command, ref int exitCode)
{
    ProcessStartInfo processInfo;
    Process process = new Process();
    string output = 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 streamReader = process.StandardOutput;
    output = streamReader.ReadToEnd();
    exitCode = process.ExitCode;
    process.Close();
    return output;
}

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

Shrink, create a partition in C# without DiskPart


Similar Articles