Invoking cmd.exe from .NET

One of the primary reasons I am writing this blog is to give back to the community -- technical blogs and message board archives have saved my bacon many times, so my plan is, whenever I spend an hour or two figuring something out and I wasn't able to find any concise resources about it, I'll write a post on it so that the next person may stumble across it and save some time.

Yesterday I was working on calling cmd.exe from within .NET, and had to piece together a few things from various places.  Here is the code I ended up with.  I've added comments to explain the reason for each line of code -- hopefully someone will find this helpful.

 

using System;
using System.Diagnostics;

namespace Utilities
{
    public class Command
    {
        public static string ExecuteCmd(string arguments)
        {
            // Create the Process Info object with the overloaded constructor
            // This takes in two parameters, the program to start and the
            // command line arguments.
            // The arguments parm is prefixed with "@" to eliminate the need
            // to escape special characters (i.e. backslashes) in the
            // arguments string and has "/C" prior to the command to tell
            // the process to execute the command quickly without feedback.
            ProcessStartInfo _info =
                new ProcessStartInfo("cmd", @"/C " + arguments);

            // The following commands are needed to redirect the
            // standard output.  This means that it will be redirected
            // to the Process.StandardOutput StreamReader.
            _info.RedirectStandardOutput = true;

            // Set UseShellExecute to false.  This tells the process to run
            // as a child of the invoking program, instead of on its own.
            // This allows us to intercept and redirect the standard output.
            _info.UseShellExecute = false;

            // Set CreateNoWindow to true, to supress the creation of
            // a new window
            _info.CreateNoWindow = true;

            // Create a process, assign its ProcessStartInfo and start it
            Process _p = new Process();
            _p.StartInfo = _info;
            _p.Start();

            // Capture the results in a string
            string _processResults = _p.StandardOutput.ReadToEnd();

            // Close the process to release system resources
            _p.Close();

            // Return the output stream to the caller
            return _processResults;
        }
    }
}

 

12 Comments

  • Hey Guy...great article on how to launch cmd.exe from within .NET. My question is how to do you convert the following line into VB.NET??

    ProcessStartInfo _info =
    new ProcessStartInfo("cmd", @"/C " + arguments);

    VB.NET does not like the "@" character!

    Thanks so much!!

    Leo Swiontek
    Software Engineer
    leo.swiontek@issinc.com

  • Good question -- C# by default parses backslashes as escape characters, so you need to put the @ character before the string to tell the compiler to interpret the string literally.

    VB.NET doesn't interpret the backslash as an escape character, so you can just take the @ sign out and it should work for you.

  • stf,

    I'm not having any problems running the code in a winforms app -- can you give me more information on the problem you are having?

  • Thanks for this code!!! It really helped me out. Been looking for this all over. I write Zebra Printer ZPL code to a text file and then need to do a "/C COPY " & path & " LPT1" to send it to the printer. Knew how in VB6, but not .net.
    Note to other readers: If your "path" contains spaces, you must wrap it in "s (quotes). Otherwise, it won't work - cmd does not like spaces in folder/file names.
    Thanks again for taking the time - it helped me. :)

  • I figured it out:
    Obviously reading the redirected Output stream needs an explicit conversion, in some cases at least.

    A call like:
    System.IO.StreamReader sr = new System.IO.StreamReader(p.StandardOutput.BaseStream, textEndcoding)

    fixed the problem for me. Reading the stream for the dir command on windows vista f***ed up basically all the digits (from windows.forms, not from console) In this case I run the command again with a changed encoding set to textEndcoding.

    I can not see a reasonable explanation for this behaviour...

  • stf -- I'm glad to hear it, that's interesting behavior. I'm back working on XP now for the near term, so I couldn't recreate that error -- it's a good thing to be aware of.

    I really appreciate you hunting it down and posting the solution back here.

  • thanks lot...plz give ur email id..for future reference...

  • Guy,
    Thanks for the code snippet and comments. This was very helpful.

  • Thanks for this post! Was really helpful.
    Comments in the code helped easily understand what's going on.

  • Using same code but ASP.NET not able run cmd at production server win 2003. i want to run sqlldr using command.

  • @Ratna,

    Your problem is possibly security related. The Windows account that is running your software must have permissions to execute sqlldr as well as access to any file folders used. You may want to try either impersonation, or modifying the security settings on your server to allow whatever user account is executing the software to also run sqlldr.

  • Very good & helpful post.

    by Fahad

Comments have been disabled for this content.