如何使用c#轻松运行shell命令?

Moh*_*dib 5 c# command-line command-line-arguments

如何使用 C# 运行命令提示符命令?假设我想按顺序运行这些命令:

cd F:/File/File2/...FileX/
ipconfig
ping google.com
Run Code Online (Sandbox Code Playgroud)

或类似的东西......有人可以做这个方法:

void runCommands(String[] commands) 
{
    //method guts...
}
Run Code Online (Sandbox Code Playgroud)

这样您的输入是一系列字符串命令(即[“ipconfig”,“ping 192.168.192.168”,“ping google.com”,“nslookup facebook.com”),应在特定的单个命令提示符下执行它们放入数组的顺序。谢谢。

Cha*_*thJ 4

应按照它们放入数组的特定顺序在单个命令提示符下执行

您可以在 bat 文件中编写命令序列并按如下方式运行。

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

参考