1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
namespace DevenvMaker
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
/// <summary>
/// A class to launch process.
/// </summary>
public class ProcessWrapper : IDisposable
{
#region Constructors
/// <summary>
/// Constructs a new instance of a process wrapper.
/// </summary>
/// <param name="command">The executable.</param>
/// <param name="args">The arguments.</param>
public ProcessWrapper(string command, params string[] args)
{
var sEscapedArgs = args.Select(x => this.EscapeArgument(x));
var sEscapedArgsCollapsed = string.Join(" ", sEscapedArgs.ToArray());
var sExecutable = Path.GetFileName(command);
this.ShortCommandLine = string.Format("{0} {1}", sExecutable, sEscapedArgsCollapsed);
this.CommandLine = string.Format("{0} {1}", command, sEscapedArgsCollapsed);
var oProcessStartInfo = new ProcessStartInfo(command, sEscapedArgsCollapsed);
oProcessStartInfo.CreateNoWindow = true;
oProcessStartInfo.RedirectStandardError = true;
oProcessStartInfo.RedirectStandardInput = true;
oProcessStartInfo.RedirectStandardOutput = true;
oProcessStartInfo.UseShellExecute = false;
this.Process = new Process();
this.Process.StartInfo = oProcessStartInfo;
this.Process.Start();
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the command line of the process.
/// </summary>
public string CommandLine
{
get;
private set;
}
/// <summary>
/// Gets the stream reader for error channel.
/// </summary>
public StreamReader Error
{
get { return this.Process.StandardError; }
}
/// <summary>
/// Gets the stream writer for standard channel.
/// </summary>
public StreamWriter Input
{
get { return this.Process.StandardInput; }
}
/// <summary>
/// Gets the stream reader for the standard channel.
/// </summary>
public StreamReader Output
{
get { return this.Process.StandardOutput; }
}
/// <summary>
/// Gets the short command line (without the full path of the executable).
/// </summary>
public string ShortCommandLine
{
get;
private set;
}
private Process Process
{
get;
set;
}
#endregion Properties
#region Methods
/// <summary>
/// Disposes the process wrapper (finish the real process).
/// </summary>
public void Dispose()
{
this.Process.Dispose();
}
private string EscapeArgument(string arg)
{
if (arg.Contains("\"") || arg.Contains(" "))
{
return string.Format("\"{0}\"", arg.Replace("\"", "\"\""));
}
else
{
return arg;
}
}
#endregion Methods
}
} |
Partager