Home > front end >  C# Create virtual disk with Subst command
C# Create virtual disk with Subst command

Time:12-22

I need to create a directory with the letter P (or whatever) so that it is like drive C or D. After trying different methods, I came to the conclusion that it is best to do this with the help of Subst. But how to do it in C#. The code I'm using doesn't work. As administrator, does not work either.

`

string diskLetter = "P:"; // <---
string path = @"D:\folder path";
 
Process.Start(new ProcessStartInfo
{
    FileName = "subst",
    Arguments = $"{diskLetter} \"{path}\"",
    Verb = "runas",
    UseShellExecute = true
});

`

CodePudding user response:

To use the subst command in C#, you can use the Process class to start a new process and run the command. Here is an example of how you can do this:

using System.Diagnostics;
// ...
string driveLetter = "P";
string path = "C:\\my\\folder\\path";

Process process = new Process();
process.StartInfo.FileName = "subst";
process.StartInfo.Arguments = $"{driveLetter}: {path}";
process.Start();

This will create a virtual drive with the letter P that maps to the folder at the specified path.

Note that you will need to have administrative privileges to create a virtual drive using subst. If the code is not working, it could be because the process is not being started with the necessary privileges. To start the process with administrative privileges, you can set the Verb property of the StartInfo object to "runas":

process.StartInfo.Verb = "runas";

CodePudding user response:

First of all I would recommend you to use CliWrap libriary, that will improve your work with cli in .NET.

I think, you should check this question to understand how to use cli (cmd) wrapping in .NET.

So let's try to remake answer in this question to help you.

Don't forget that subst is command that requires the admin privileges, so.

string driveLetter = "P";
string path = "C:\\my\\folder\\path";

Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = $"/C copy subst {driveLetter}: {path}";
startInfo.Verb = "runas";

process.StartInfo = startInfo;
process.Start();
  • Related