Created
July 6, 2022 14:59
-
-
Save emoacht/6404e00b5b4637601118fd1fa6228d31 to your computer and use it in GitHub Desktop.
Execute command in .NET 5.0 and newer.
This file contains 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
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