Skip to content

Instantly share code, notes, and snippets.

@mhutch mhutch/TestMain.cs
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 }
);
p.WaitForExit ();
Environment.Exit (p.ExitCode);
}
}
/// <summary>
/// Builds a process argument string.
/// </summary>
public class ProcessArgumentBuilder
{
StringBuilder sb = new StringBuilder ();
// .NET doesn't allow escaping chars other than " and \ inside " quotes
static string escapeDoubleQuoteCharsStr = "\\\"";
/// <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, escapeDoubleQuoteCharsStr, 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 escapeChars, string s)
{
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (escapeChars.IndexOf (c) > -1)
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.