-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleProcess.cs
80 lines (66 loc) · 2.42 KB
/
ConsoleProcess.cs
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
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Trace = ScriptCommander.Core.Trace;
namespace ScriptCommander
{
public class ConsoleProcess
{
private Process Process { get; set; }
private readonly ProcessStartInfo _startInfo;
public StreamWriter Input { get; set; }
private readonly ISubject<char> _standartOutput = new Subject<char>();
private readonly ISubject<char> _errorOutput = new Subject<char>();
public IObservable<char> StandartOutput { get { return _standartOutput; } }
public IObservable<char> ErrorOutput { get { return _errorOutput; } }
public ConsoleProcess(ProcessStartInfo startInfo)
{
_startInfo = startInfo;
_startInfo.RedirectStandardInput = true;
_startInfo.RedirectStandardOutput = true;
_startInfo.RedirectStandardError = true;
_startInfo.CreateNoWindow = true;
_startInfo.UseShellExecute = false;
_startInfo.StandardOutputEncoding = Encoding.GetEncoding(866);
}
public void Start()
{
System.Diagnostics.Trace.Write(_startInfo.FileName);
System.Diagnostics.Trace.Write(" ");
System.Diagnostics.Trace.WriteLine(_startInfo.Arguments);
Process = new Process
{
StartInfo = _startInfo,
EnableRaisingEvents = true,
};
Process.Start();
Input = Process.StandardInput;
Action<StreamReader, ISubject<char>> readToSubject = (reader, subject) =>
{
char s;
while (Process != null && !Process.HasExited && (s = (char)reader.Read()) != '\0')
{
subject.OnNext(s);
}
};
Task.Factory.StartNew(() => readToSubject(Process.StandardOutput, _standartOutput));
Task.Factory.StartNew(() => readToSubject(Process.StandardError, _errorOutput));
}
public void Close()
{
if (!Process.HasExited)
{
Process.CloseMainWindow();
Process.Close();
}
Process = null;
}
}
}