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
thanks , it works well