I'm trying to run a process using diskpart, but to do that I need administrator privileges because I'm using a PC at my work. In order to run a Process as administrator I need Process.StartInfo.Verb = "runas" and I also need Process.StartInfo.UseShellExecute = true. With UseShellExecute set to true, I can't pass commands to standard input, but if I set it to false, I get an error saying "The requested operation requires elevation" (aka I need admin privileges). If I try passing a script to in Process.StartInfo.Arguments it doesn't seem to do anything. Here are a couple versions of the code I have tried out so far (none of them have worked):
Version 1:
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = @"C:\Windows\System32\diskpart.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = "vhdScript.txt";
p.Start();
Version 2:
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = @"C:\Windows\System32\diskpart.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = "/s vhdScript.txt";
p.Start();
Version 3:
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = "/c diskpart /s vhdScript.txt";
p.Start();
Version 4:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = "/c diskpart";
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine("select vdisk 1");
Any thoughts? Thanks.
The following shows how to create a diskpart script and then use System.Diagnostics.Process to execute the script.
Create a new
Windows Forms App (.NET Framework)
project (name: ProcessDiskPartTest)Add an Application Manifest to your project
Note: This is used to prompt the user to execute the program as Administrator.
In app.manifest, replace
with
Add the following using statements:
using System.IO;
using System.Diagnostics;
The following code will use Process to execute
diskpart
script.Below, shows how to add a diskpart script as an embedded resource.
Create a folder for your DiskPart script(s)
Add DiskPart script to project
Note: The diskpart script below is only for testing purposes. Rename it to your desired name and replace the commands with your desired diskpart command(s).
DiskPartListDisk.txt
Make text file an embedded resource
The following is used to read an embedded text file.
Create a class (name: HelperLoadResource.cs)
HelperLoadResource.cs
Note: The code for "ReadResource" is from here.
Usage:
Resources: