Executing Command Line Process from C# Code

Created: May 4, 2017 Tagged As: C#, Language Share:

When programming lately, I find that virtually everything I need to do has a nice programmatic wrapper (application programming interface, or API) of some sort. But occasionally, I find that the only option I have is to mimic typing dreaded command line entries with code.

I find it oddly scary to need to type letters in a dark and forbidding window to get something done. For example, I would much rather pull up "This PC" than see this:

Though I must admit that for certain repetitive tasks, scripting out DOS commands can be advantageous.

 

So what happens when you find that a DOS command is your only option and you need to execute it in some code? I recently ran into this when trying to auto-publish some NuGet packages to my private feed...

Running NuGet.exe In C#

Luckily, running external processes is quite simple using Process.Start.

var info = new System.Diagnostics.ProcessStartInfo
{
    FileName = @"C:\Projects\DecisiveComputing\nuget.exe",
    Arguments = $"push {info.FullName} mykey -source https://mynugetfeed"
};
System.Diagnostics.Process.Start(info);

 

This works, but man is it sloppy. The program flashes a DOS command window briefly while NuGet.exe runs. Plus, we have no idea if the process was successful or not.

Running NuGet.exe in C# - Properly

With some modifications, we can make our NuGet.exe run as though it is a native part of our program (or as "native" as a command-line based process can be).

var info = new System.Diagnostics.ProcessStartInfo
{
    FileName = @"C:\Projects\DecisiveComputing\nuget.exe",
    Arguments = $"push {info.FullName} mykey -source https://mynugetfeed",
    CreateNoWindow = true,
    WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
    RedirectStandardOutput = true,
    UseShellExecute = false
};
var p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
string results = p.StandardOutput.ReadToEnd();

 

With these changes, we have prevented any and all user interface elements from appearing. Furthermore, all output from the program has been redirected to our program so that we can process it.

This time, upon calling Process.Start, we obtain a reference to the Process that was started for two reasons: 1) we want to wait for it to complete (p.WaitForExit) so that we can 2) grab the output as a string (p.StandardOutput.ReadToEnd) that we can parse as needed.