Created
April 29, 2014 22:01
-
-
Save mhutch/11413092 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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