Created
February 26, 2020 20:28
-
-
Save ZacharyPatten/53c89867e9fa968c76d28e0f273bbbb4 to your computer and use it in GitHub Desktop.
Example of running commands in Windows from C#
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; | |
class Program | |
{ | |
static void Main() | |
{ | |
WindowsCmdCommand.Run("dir", out string output, out string error); | |
Console.WriteLine("OUTPUT: " + output); | |
Console.WriteLine("ERROR: " + error); | |
Console.ReadLine(); | |
} | |
} | |
public static class WindowsCmdCommand | |
{ | |
public static void Run(string command, out string output, out string error, string directory = null) | |
{ | |
using Process process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = "cmd.exe", | |
UseShellExecute = false, | |
RedirectStandardOutput = true, | |
RedirectStandardError = true, | |
RedirectStandardInput = true, | |
Arguments = "/c " + command, | |
CreateNoWindow = true, | |
WorkingDirectory = directory ?? string.Empty, | |
} | |
}; | |
process.Start(); | |
process.WaitForExit(); | |
output = process.StandardOutput.ReadToEnd(); | |
error = process.StandardError.ReadToEnd(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Amazing Piece of code to work with CMD Commands Simultaneously, with out having to open a CMD and have pressed keys.
I Am going to try to Semi Recreate this to work with other applications such as, Interaction with Task manager and maybe some others.