Taylor Brown
Taylor Brown

Reputation: 13

Making directories with command line on C#

System.Diagnostics.Process process = new System.Diagnostics.Process ();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo ();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "md " + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
process.StartInfo = startInfo;
process.Start ();

I'm attempting to make a directory on the desktop with this command, it doesn't make one however. Can anyone tell me why?

Upvotes: 0

Views: 1451

Answers (1)

rory.ap
rory.ap

Reputation: 35260

Just do this:

Directory.CreateDirectory(Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), 
    "my new folder name"));

Always prefer using the .NET class library instead of invoking external processes to do your work, unless you have a very specific reason not to do so.


One of the reasons your code is not working is because you are using the wrong syntax for cmd.exe. In order to pass a command as an argument, you have to use the following with the /K switch (use cmd /? for more information):

cmd.exe /K MD "c:\test\blah"

Another reason your code won't work is that the path you're providing to the MD command is just the path to the desktop itself:

Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

You have forgotten to append the name of the folder you want to create on the desktop.

Upvotes: 3

Related Questions