如何从c#中执行cmd命令
本文关键字:执行 cmd 命令 | 更新日期: 2023-09-27 18:08:15
我想在我的c#应用程序的cmd上运行命令。
I tried:
string strCmdText = "ipconfig";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
结果:弹出CMD窗口,但命令没有执行任何操作。
为什么?
使用
System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig");
如果您希望cmd仍然打开,请使用:
System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig");
from codeproject
public void ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
}