Created
March 25, 2022 13:34
-
-
Save savaged/64b2df9806167bc460aec20a5c84ec33 to your computer and use it in GitHub Desktop.
C# wrapped terminal/console command
This file contains hidden or 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.Diagnostics; | |
| using System.Text; | |
| namespace Savaged.ConsoleWrapping | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var app = new App(); | |
| app.Run(); | |
| Console.WriteLine(app.Output); | |
| Console.ReadLine(); | |
| } | |
| } | |
| class App | |
| { | |
| private readonly StringBuilder _out; | |
| public App() | |
| { | |
| _out = new StringBuilder(); | |
| } | |
| public string Output => _out.ToString(); | |
| public void Run() | |
| { | |
| using (var p = new Process()) | |
| { | |
| p.StartInfo = new ProcessStartInfo | |
| { | |
| FileName = "C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe", | |
| Arguments = "--help", | |
| UseShellExecute = false, | |
| RedirectStandardOutput = true, | |
| RedirectStandardError = true | |
| }; | |
| p.OutputDataReceived += (s, e) => AddOutput(e); | |
| p.ErrorDataReceived += (s, e) => AddOutput(e); | |
| p.Start(); | |
| p.BeginOutputReadLine(); | |
| p.BeginErrorReadLine(); | |
| p.WaitForExit(); | |
| } | |
| } | |
| private void AddOutput(DataReceivedEventArgs e) | |
| { | |
| lock (_out) | |
| { | |
| _out.Append(e.Data); | |
| _out.Append(Environment.NewLine); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment