How to parse command line output from c#?
There is one more way of getting all the output as events as and when they are output by the other console application cmd_DataReceived
gets raised whenever there is output and cmd_Error
gets raised whenever there is an error raised in the other application.
If you want to parse the output, probably handling these events is a better way to read output and handle errors in the other application as and when they occur.
using System;
using System.Diagnostics;
namespace InteractWithConsoleApp
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.bing.com"); //Execute ping bing.com
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
}
}
Parse console output in c#
I think you want to make a general modification to your console's output, for example if a Serie
goes to output, you want write a message before it. so your code might be such this:
class MyWriter : TextWriter
{
private TextWriter originalOut;
public MyWriter()
{
originalOut = Console.Out;
}
public override Encoding Encoding
{
get { return new System.Text.ASCIIEncoding(); }
}
public override void WriteLine(string message)
{
originalOut.WriteLine(CheckMySerie(message));
}
public override void Write(string message)
{
originalOut.Write(CheckMySerie(message));
}
private string CheckMySerie(string message)
{
if (message.Contains("MySerie"))
return "My Serie has been found\n" + message;
else
return message;
}
}
class Program
{
static void Main(string[] args)
{
Console.SetOut(new MyWriter());
Console.WriteLine("test 1 2 3");
Console.WriteLine("test MySerie 2 3");
Console.ReadKey();
}
}
Best way to parse command line arguments in C#?
I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:
bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;
var p = new OptionSet () {
{ "n|name=", "the {NAME} of someone to greet.",
v => names.Add (v) },
{ "r|repeat=",
"the number of {TIMES} to repeat the greeting.\n" +
"this must be an integer.",
(int v) => repeat = v },
{ "v", "increase debug message verbosity",
v => { if (v != null) ++verbosity; } },
{ "h|help", "show this message and exit",
v => show_help = v != null },
};
List<string> extra;
try {
extra = p.Parse (args);
}
catch (OptionException e) {
Console.Write ("greet: ");
Console.WriteLine (e.Message);
Console.WriteLine ("Try `greet --help' for more information.");
return;
}
Parse command line string into a list of strings
This class satisfies the requirements. It's not the most effective way, but it returns the right arguments.
public static class ArgumentLineParser
{
public static string[] ToArguments(string cmd)
{
if (string.IsNullOrWhiteSpace(cmd))
{
return new string[0];
}
var argList = new List<string>();
var parseStack = new Stack<char>();
bool insideLiteral = false;
for (int i = 0; i < cmd.Length; i++)
{
bool isLast = i + 1 >= cmd.Length;
if (char.IsWhiteSpace(cmd[i]) && insideLiteral)
{
// Whitespace within literal is kept
parseStack.Push(cmd[i]);
}
else if (char.IsWhiteSpace(cmd[i]))
{
// Whitespace delimits arguments
MoveArgumentToList(parseStack, argList);
}
else if (!isLast && '\\'.Equals(cmd[i]) && '"'.Equals(cmd[i + 1]))
{
//Escaped double quote
parseStack.Push(cmd[i + 1]);
i++;
}
else if ('"'.Equals(cmd[i]) && !insideLiteral)
{
// Begin literal
insideLiteral = true;
}
else if ('"'.Equals(cmd[i]) && insideLiteral)
{
// End literal
insideLiteral = false;
}
else
{
parseStack.Push(cmd[i]);
}
}
MoveArgumentToList(parseStack, argList);
return argList.ToArray();
}
private static void MoveArgumentToList(Stack<char> stack, List<string> list)
{
var arg = string.Empty;
while (stack.Count > 0)
{
arg = stack.Pop() + arg;
}
if (arg != string.Empty)
{
list.Add(arg);
}
}
}
It can be used like this:
var line = @"first-arg second-arg ""third arg with spaces"" ""arg with \"" quotes""";
var args = ArgumentLineParser.ToArguments(line);
Related Topics
How to Hide an Inherited Property in a Class Without Modifying the Inherited Class (Base Class)
JSON.Net Serialize Directly from Oledbconnection
Easier Way of Writing Null or Empty
C# Winforms: How to Set Main Function Stathreadattribute
Get the Id of Inserted Row Using C#
Generic C# Code and the Plus Operator
Using Tfs API, How to Find the Comments Which Were Made on a Code Review
Interesting "Params of Ref" Feature, Any Workarounds
ASP.NET How to Stream File to User
How to Access Ssis Package Variables Inside Script Component
Store Complex Object in Tempdata
Error Making Azure Management Library API Call When Authenticating with Azure Active Directory