Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created July 6, 2022 14:59
Show Gist options
  • Save emoacht/6404e00b5b4637601118fd1fa6228d31 to your computer and use it in GitHub Desktop.
Save emoacht/6404e00b5b4637601118fd1fa6228d31 to your computer and use it in GitHub Desktop.
Execute command in .NET 5.0 and newer.
public static async Task<string[]> ExecuteCommandAsync(string command)
{
using var p = new Process();
p.StartInfo = new ProcessStartInfo("cmd.exe")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
p.Start();
using var sw = p.StandardInput;
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("chcp 437");
sw.WriteLine(command);
sw.WriteLine("exit");
}
await p.WaitForExitAsync();
var buffer = new List<string>();
using var sr = p.StandardOutput;
if (sr.BaseStream.CanRead)
{
while (sr.Peek() >= 0)
{
buffer.Add(sr.ReadLine()!);
}
}
return buffer.SkipLast(1).ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment