-
-
Save mhutch/edb01e3333b7480381c4 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, 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