Skip to content

Instantly share code, notes, and snippets.

@mhutch mhutch/TestMain.cs Secret
Created Apr 29, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.