Skip to content

Instantly share code, notes, and snippets.

@savaged
Created March 25, 2022 13:34
Show Gist options
  • Select an option

  • Save savaged/64b2df9806167bc460aec20a5c84ec33 to your computer and use it in GitHub Desktop.

Select an option

Save savaged/64b2df9806167bc460aec20a5c84ec33 to your computer and use it in GitHub Desktop.
C# wrapped terminal/console command
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