-
Notifications
You must be signed in to change notification settings - Fork 0
/
TerminalHelper.cs
56 lines (50 loc) · 1.71 KB
/
TerminalHelper.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Scalizer
{
internal class TerminalHelper
{
public static string execute(string command)
{
var startInfo = new ProcessStartInfo
{
FileName = "C:\\WINDOWS\\system32\\cmd.exe", // use cmd for example, you can run your own test.bat
Verb = "runas", // run as administrator
Arguments = "/C " + command,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
var cmd = new Process();
cmd.StartInfo = startInfo;
var output = new StringBuilder();
// set output hander
cmd.OutputDataReceived += (sender, args) => output.AppendLine(args.Data);
string stdError = "";
try
{
cmd.Start();
// get standard output asynchronously
cmd.BeginOutputReadLine();
// get standard error synchronously
stdError = cmd.StandardError.ReadToEnd();
cmd.WaitForExit();
}
catch (Exception e)
{
throw new Exception("OS error while executing: " + e.Message);
}
if (cmd.ExitCode != 0)
{
throw new Exception("Finished with exit code = " + cmd.ExitCode + ": " + stdError);
}
return output.ToString();
}
}
}