forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSynchronizedProcessReader.cs
81 lines (67 loc) · 2.62 KB
/
SynchronizedProcessReader.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
81
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace GitCommands
{
public static class SynchronizedProcessReader
{
/// <summary>
/// This function reads the output to a string. This function can be dangerous, because it returns a string
/// and needs to know the correct encoding. This function should be avoided!
/// </summary>
public static void Read(Process process, out string stdOutput, out string stdError)
{
string stdOutputLoader = null;
Thread stdOutputLoaderThread = new Thread(_ => stdOutputLoader = process.StandardOutput.ReadToEnd());
stdOutputLoaderThread.Start();
stdError = process.StandardError.ReadToEnd();
stdOutputLoaderThread.Join();
stdOutput = stdOutputLoader;
}
/// <summary>
/// This function reads the output to a byte[]. This function is used because it doesn't need to know the
/// corract encoding.
/// </summary>
public static void ReadBytes(Process process, out byte[] stdOutput, out byte[] stdError)
{
byte[] stdOutputLoader = null;
//We cannot use the async functions because these functions will read the output to a string, this
//can cause problems because the correct encoding is not used.
Thread stdOutputLoaderThread = new Thread(_ => stdOutputLoader = ReadByte(process.StandardOutput.BaseStream));
stdOutputLoaderThread.Start();
stdError = ReadByte(process.StandardError.BaseStream);
stdOutputLoaderThread.Join();
stdOutput = stdOutputLoader;
}
private static byte[] ReadByte(Stream stream)
{
if (!stream.CanRead)
{
return null;
}
int commonLen = 0;
List<byte[]> list = new List<byte[]>();
byte[] buffer = new byte[4096];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) != 0)
{
byte[] newbuff = new byte[len];
Array.Copy(buffer, newbuff, len);
commonLen += len;
list.Add(newbuff);
}
buffer = new byte[commonLen];
commonLen = 0;
for (int i = 0; i < list.Count; i++)
{
Array.Copy(list[i], 0, buffer, commonLen, list[i].Length);
commonLen += list[i].Length;
}
return buffer;
}
}
}