HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to run Command Prompt commands from C#

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
promptrunhowfromcommandscommand

Problem

Is there any way to run command prompt commands from within a C# application? If so how would I do the following:

copy /b Image1.jpg + Archive.rar Image2.jpg


This basically embeds an RAR file within JPG image. I was just wondering if there was a way to do this automatically in C#.

Solution

this is all you have to do run shell commands from C#

string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);


EDIT:

This is to hide the cmd window.

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 = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();


EDIT 2:

It is important that the argument begins with /C, otherwise it won't work. As @scott-ferguson said: /C carries out the command specified by the string and then terminates.

Code Snippets

string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
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 = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();

Context

Stack Overflow Q#1469764, score: 1177

Revisions (0)

No revisions yet.