By user


2009-09-24 04:24:45 8 Comments

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#.

13 comments

@Elad 2019-12-08 11:46:25

if you want to run the command in async mode - and print the results. you can you this class:

    public static class ExecuteCmd
{
    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    public static void ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            // The following commands are needed to redirect the standard output. 
            //This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput =  true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            string result = proc.StandardOutput.ReadToEnd();

            // Display the command output.
            Console.WriteLine(result);
        }
        catch (Exception objException)
        {
            // Log the exception
            Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
        }
    }

    /// <summary>
    /// Execute the command Asynchronously.
    /// </summary>
    /// <param name="command">string command.</param>
    public static void ExecuteCommandAsync(string command)
    {
        try
        {
            //Asynchronously start the Thread to process the Execute command request.
            Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
            //Make the thread as background thread.
            objThread.IsBackground = true;
            //Set the Priority of the thread.
            objThread.Priority = ThreadPriority.AboveNormal;
            //Start the thread.
            objThread.Start(command);
        }
        catch (ThreadStartException )
        {
            // Log the exception
        }
        catch (ThreadAbortException )
        {
            // Log the exception
        }
        catch (Exception )
        {
            // Log the exception
        }
    }

}

@Uniquedesign 2019-02-13 13:42:19

if you want to keep the cmd window open or want to use it in winform/wpf then use it like this

    string strCmdText;
//For Testing
    strCmdText= "/K ipconfig";

 System.Diagnostics.Process.Start("CMD.exe",strCmdText);

/K

Will keep the cmd window open

@pius 2019-07-16 10:55:23

Nice. Found this documentation for cmd command and its parameters.

@XMMR12 2018-12-07 03:08:35

you can use simply write the code in a .bat format extension ,the code of the batch file :

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

use this c# code :

Process.Start("file_name.bat")

@XMMR12 2018-12-07 03:37:27

if you want to hide the cmd while running you can use a simple visual basic script code in a .vbs format extension ,the code : CreateObject("Wscript.Shell").Run "filename.bat",0,True

@RameshVel 2009-09-24 04:34:40

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

Important is that the argument begins with /C otherwise it won't work. How Scott Ferguson said: it "Carries out the command specified by the string and then terminates."

@user 2009-09-24 04:42:22

That works great! Can I just ask what the "/C" is for?

@Scott Ferguson 2009-09-24 04:48:18

/C Carries out the command specified by string and then terminates

@RameshVel 2009-09-24 04:49:08

its just to tell the cmd to run and terminate (dont wait for any user input to close the window)

@user 2009-09-24 04:53:53

Thank you, one more question. Is there a way to hide the the command prompt during this?

@RameshVel 2009-09-24 05:13:48

@Nate, i have updated my answer for ur comments. pls check out

@user 2009-09-24 05:27:58

Thank you so very much. One more question lol, I'm sorry. Currently, the program has to be ran in the same directory that the files are. Is there a way to make it so the files can be in different directories? Examples: C:\Image1.jpg + C:\Directory1\Archive.rar C:\Directory2\Image2.jpg

@RameshVel 2009-09-24 05:48:40

CMD accpets the complete path... try to execute this in command line iteslf and check.. because normal copy operation like this works "copy d:\web.config d:\w5.config"; perfectly..

@user 2009-09-24 06:04:34

Don't I have to change the "C:\" to "C:\\"? I had to do that to get it to run. It still doesn't want to work though...

@RameshVel 2009-09-24 06:28:35

i just tested this.. "copy /b c:\Image1.jpg + d:\archive.rar d:\image2.jpg".. it works finr

@user 2009-09-24 07:03:24

Ok, I found out what the problem is. I folders that the files were in were under the C:\Documents and Settings\ in a subdirectory. I guess it is because of the spaces in the directory name?

@Instance Hunter 2009-09-25 18:04:22

I don't see how I'm the only one that thinks this is a horrible idea. Yes, this will work, but it's completely and totally wrong. Spawning CMD processes to do simple IO operations is wrong, even if it works. Read through the documentation on the System.IO namespace. There is more than enough functionality in there to do what you need to do without spawning unneeded processes.

@nawfal 2011-04-15 18:38:22

This works smooth. Exactly what i wanted.. @Daniel, u are right. But I needed this CMD process since I could do only using command prompt. Hiding the window etc worked fine.

@Mikhail 2012-10-25 09:10:29

Fortunately, this call also properly handles spaces, quotes, stream redirections and process exit code! Wonderful, thanks!

@monish001 2013-05-10 07:17:52

I tried with 'dir' command. But I only see the command prompt opening up and it does not execute the command. string cmdStr = "dir"; System.Diagnostics.Process.Start("CMD.exe", cmdStr);

@Cyril Gupta 2013-09-10 12:12:58

This doesn't work in Windows 8 because the command prompt won't have elevated privileges (administrative rights)

@RameshVel 2013-09-10 14:09:44

@CyrilGupta, i haven't checked in win 8. But to avoid that you can run your exe under admin privilege.

@shindigo 2014-04-01 17:48:57

FYI: Use process.WaitForExit() to wait for the process to complete before continuing and process.ExitCode to get the exit code of the process.

@Ogglas 2015-09-30 17:07:25

Anyone else experiencing problems passing arguments? I have tried running VS both as Administrator and normal user. cmd starts but no arguments are passed.

@Murali Murugesan 2016-01-04 16:48:29

Tried copying to the network path and getting Access Denied error. Here is my post

@barlop 2016-04-24 12:30:52

i'd note that it seems(perhaps expectedly!) that these console hiding methods.. won't work if the project itself is a console application ;-) (at least not when clicking play in visual studio, for a console application!)

@Peter Huber 2016-06-30 17:11:39

You should dispose the process resources: using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); }

@Laurynas Lazauskas 2016-07-22 09:40:27

Don't forget the "/C" when using process.WaitForExit(). Otherwise your application will hang.

@user5950947 2016-07-25 08:45:25

How can I get the response given by the cmd. Like if I am executing a program input by user and giving command like - Node a.js, cms will generate an output. How can I get that?

@RameshVel 2016-07-25 18:14:44

@Cool888, something like this stackoverflow.com/questions/1390559/…

@Dr. Funk 2017-06-29 21:36:42

"Read through the documentation on the System.IO namespace. There is more than enough functionality in there to do what you need to do without spawning unneeded processes" If I want to use UAC to elevate just before running some command from my application, but I don't want my application to always be elevated, then running commands this way is essentially the only option.

@N.K 2018-04-10 03:34:20

how can i add this command , REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f after adding this with escape chars , it stops working ...

@Appu Mistri 2018-07-25 18:50:52

Any idea how can I do this in Linux, I believe cmd.exe will not work for Linux, I need a solution which works for both Windows and Linux.

@shA.t 2018-08-13 09:51:21

And in some cases you need to set ProcessStartInfo.UseShellExecute = true -HTH ;).

@Mustafa Alan 2018-10-12 15:46:36

So how can I catch when this process is end?

@RameshVel 2018-10-15 05:43:40

@Rufus L 2019-01-26 01:08:07

@InstanceHunter This comes in handy when needing to rename directories when you're only changing the case. Using System.IO requires you to call Directory.Move twice - once to rename it to something else, then again to rename it to the proper casing, whereas using cmd.exe /c ren "c:\foo\bar" "Bar" works without all that. But if you know a better way, please let me know, cause otherwise I don't like this either.

@Peter verleg 2018-02-18 19:59:43

You can achieve this by using the following method (as mentioned in other answers):

strCmdText = "'/C some command";
Process.Start("CMD.exe", strCmdText);

When I tried the methods listed above I found that my custom command did not work using the syntax of some of the answers above.

I found out more complex commands need to be encapsulated in quotes to work:

string strCmdText;
strCmdText = "'/C cd " + path + " && composer update && composer install -o'";
Process.Start("CMD.exe", strCmdText);

@Tyrrrz 2017-10-29 17:33:23

You can do this using CliWrap in one line:

var stdout = new Cli("cmd")
         .Execute("copy /b Image1.jpg + Archive.rar Image2.jpg")
         .StandardOutput;

@Zach Smith 2018-05-11 14:33:50

I upvoted this... but the repo seems to be missing now: Unable to find package 'CliWrap' at source

@Tyrrrz 2018-05-12 14:39:59

@ZachSmith not sure what you mean, nuget.org/packages/CliWrap seems to work fine. The original link too.

@Zach Smith 2018-05-15 12:23:22

Ah.sorry.. for some reason when I couldn't connect to my nuget repo over vpn I was unable to install this package. nuget is still mostly a mystery to me. must have set it up wrong

@Matt Bonness 2017-01-24 04:01:38

None of the above answers helped for some reason, it seems like they sweep errors under the rug and make troubleshooting one's command difficult. So I ended up going with something like this, maybe it will help someone else:

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = @"C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\tf.exe",
        Arguments = "checkout AndroidManifest.xml",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        WorkingDirectory = @"C:\MyAndroidApp\"
    }
};

proc.Start();

@script'n'code 2017-05-08 04:52:31

If i would want to compile this into a stand-alone console application, what other code would have to be added to make it work? (i'm a noob to all this programming stuff, only done some scripting). I'm using csc.exe btw.

@coinbird 2017-08-28 16:01:03

@copyitright A namespace and class. If you just create a new project they will be generated for you.

@Zach Smith 2018-05-11 14:40:28

Ah. nevermind. if you use the cmd.exe app you can pass commands as arguments.

@Minh Tran 2018-10-12 17:31:04

For posterity: I wanted the process to run echo Hello World! and display the command output in the cmd window that pops up . So I tried: Filename = @"echo", Arguments = "Hello World!", UseShellExecute = false, RedirectStandardOuput = false, CreateNoWindow = false. This allowed the cmd window of the parent application to display "Hello World!" (which makes sense because stdout was not redirected to the child process).

@Slai 2016-08-25 01:26:32

with a reference to Microsoft.VisualBasic

Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);

@HackerMan 2014-04-04 17:52:53

var proc1 = new ProcessStartInfo();
string anyCommand; 
proc1.UseShellExecute = true;

proc1.WorkingDirectory = @"C:\Windows\System32";

proc1.FileName = @"C:\Windows\System32\cmd.exe";
proc1.Verb = "runas";
proc1.Arguments = "/c "+anyCommand;
proc1.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(proc1);

@Pacerier 2015-04-02 10:30:36

What's the @ sign in C#?

@James Ko 2015-04-03 01:42:59

@Pacerier It tells the compiler to escape all the characters that would normally have to be escaped in the string, in this case \. So, without the \, your code would look like proc1.FileName = "C:\\Windows\\System32\\cmd.exe";

@Pacerier 2015-04-06 13:54:30

@JamesKo, Ah found it: stackoverflow.com/q/556133/632951 . Google is still pretty lousy on symbols.

@Dinei 2018-01-10 16:41:10

One should note that proc1.Verb = "runas"; makes this process run with elevated privileges... This is not always intended.

@Hrvoje T 2018-09-13 11:26:10

How can I make this cmd window doesn't close after it is finished?

@Nazim Turakulov 2018-12-16 00:15:51

I found that calling 'cd path' joined by '&&' with other commands in the line always executes last even if it gone first. your: 'proc1.WorkingDirectory = @"C:\Windows\System32";' was very helpful! Thanks!

@pius 2019-07-16 10:59:27

@HrvojeT use /k in place of /c. See cmd doc

@kamalpreet 2015-12-02 06:03:13

Here is little simple and less code version. It will hide the console window too-

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.Start();

@Ogglas 2015-09-30 17:22:43

Tried @RameshVel solution but I could not pass arguments in my console application. If anyone experiences the same problem here is a solution:

using System.Diagnostics;

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();

cmd.StandardInput.WriteLine("echo Oscar");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

@Pete Kozak 2015-12-30 15:48:55

well I gave it no chance thinking that on my machine there are some admin or anti virus restrictions but.. the code above works! thanks Ogglas

@Ganesh Kamath - 'Code Frenzy' 2016-02-08 05:23:41

this line: cmd.StartInfo.CreateNoWindow = true; saved my day.

@Zach Smith 2018-05-11 14:50:18

Is there a way of executing multiple commands in a single cmd.StandardInput.WriteLine(@"cd C:\Test; pwd")

@CarllDev 2014-03-04 09:37:41

Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.

This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:

private void CombineFiles(string jpgFileName, string zipFileName)
{
    using (Stream original = new FileStream(jpgFileName, FileMode.Append))
    {
        using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
        {
            var buffer = new byte[32 * 1024];

            int blockSize;
            while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
            {
                original.Write(buffer, 0, blockSize);
            }
        }
    }
}

@Instance Hunter 2009-09-24 04:30:48

Yes, there is (see link in Matt Hamilton's comment), but it would be easier and better to use .NET's IO classes. You can use File.ReadAllBytes to read the files and then File.WriteAllBytes to write the "embedded" version.

@Konstantin Spirin 2009-09-24 05:34:39

Loading whole files into memory just to append one to another is not very efficient, especially if files are big enough.

@Instance Hunter 2009-09-25 18:01:52

Try to look at the spirit of the answer. The point is that .NET has more than enough IO classes and functions to do this without having to call out to the OS shell. The particular functions I mentioned may not be the best, but those were just the simplest. It doesn't make any sense at all to call out to the shell to do this.

Related Questions

Sponsored Content

47 Answered Questions

[SOLVED] How do I import an SQL file using the command line in MySQL?

14 Answered Questions

[SOLVED] How do I set a variable to the output of a command in Bash?

32 Answered Questions

[SOLVED] How do I parse command line arguments in Bash?

63 Answered Questions

[SOLVED] Calling an external command from Python

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

32 Answered Questions

[SOLVED] How to create an empty file at the command line in Windows?

18 Answered Questions

[SOLVED] Is there a way to check if a file is in use?

24 Answered Questions

[SOLVED] Is there an equivalent of 'which' on the Windows command line?

8 Answered Questions

[SOLVED] List all environment variables from the command line

Sponsored Content