Skip to content

Instantly share code, notes, and snippets.

@mhutch
Created April 29, 2014 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhutch/edb01e3333b7480381c4 to your computer and use it in GitHub Desktop.
Save mhutch/edb01e3333b7480381c4 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
public static class TestMain
{
static void Main(string[] args)
{
var pb = new ProcessArgumentBuilder();
pb.AddQuoted(args.Skip(1));
var p = Process.Start(
new ProcessStartInfo(args[0], pb.ToString()) { UseShellExecute = false, RedirectStandardOutput = true }
);
p.WaitForExit();
string s = p.StandardOutput.ReadToEnd();
Environment.Exit(p.ExitCode);
}
}
/// <summary>
/// Builds a process argument string.
/// </summary>
public class ProcessArgumentBuilder
{
static bool isMono = System.Type.GetType ("Mono.Runtime") != null;
StringBuilder sb = new StringBuilder();
/// <summary>Adds an argument, quoting and escaping as necessary.</summary>
/// <remarks>The .NET process class does not support escaped
/// arguments, only quoted arguments with escaped quotes.</remarks>
public void AddQuoted(string argument)
{
if (argument == null)
return;
if (sb.Length > 0)
sb.Append(' ');
sb.Append('"');
AppendEscaped(sb, argument);
sb.Append('"');
}
/// <summary>
/// Adds multiple arguments, quoting and escaping each as necessary.
/// </summary>
public void AddQuoted(IEnumerable<string> args)
{
foreach (var a in args)
AddQuoted(a);
}
public override string ToString()
{
return sb.ToString();
}
static void AppendEscaped(StringBuilder sb, string s)
{
for (int i = 0; i < s.Length; i++){
char c = s[i];
if (c == '"' || (isMono && c == '\\'))
sb.Append('\\');
sb.Append(c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment