我需要在c#中启动一个
cmd
命令,例如:Echo Test
。
接下来我想在消息框中显示
CMD
的输出,如下所示:
MessageBox.Show(output_of_cmd_command);
可能吗?如果是的话,怎么办?
这将包括几个步骤:
我最近使用这个函数为Python做了一些事情:
请记住,我通过设置
UseShellExecute
和 CreateNoWindow
明确抑制了 CMD 对话框本身。如果您愿意,可以更改这些。
private string RunCommand(string fileName, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = fileName;
start.Arguments = string.Format("{0}", args);
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.UseShellExecute = false;
start.CreateNoWindow = true;
var sb = new StringBuilder();
using (Process process = new Process())
{
process.StartInfo = start;
process.OutputDataReceived += (sender, eventArgs) =>
{
sb.AppendLine(eventArgs.Data); //allow other stuff as well
};
process.ErrorDataReceived += (sender, eventArgs) => {
};
if (process.Start())
{
process.EnableRaisingEvents = true;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
//allow std out to be flushed
Thread.Sleep(100);
}
}
return sb.ToString();
}
用途:
var result = RunCommand("path to your cmd.exe", "/C c:\example.bat");
MessageBox.Show(result);
以下是 CMD 选项列表:
Starts a new instance of the Windows command interpreter
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
/S Modifies the treatment of string after /C or /K (see below)
/Q Turns echo off
/D Disable execution of AutoRun commands from registry (see below)
/A Causes the output of internal commands to a pipe or file to be ANSI
/U Causes the output of internal commands to a pipe or file to be
Unicode
/T:fg Sets the foreground/background colors (see COLOR /? for more info)
/E:ON Enable command extensions (see below)
/E:OFF Disable command extensions (see below)
/F:ON Enable file and directory name completion characters (see below)
/F:OFF Disable file and directory name completion characters (see below)
/V:ON Enable delayed environment variable expansion using ! as the
delimiter. For example, /V:ON would allow !var! to expand the
variable var at execution time. The var syntax expands variables
at input time, which is quite a different thing when inside of a FOR
loop.
/V:OFF Disable delayed environment expansion.
public string ExecuteCommandPromptQuery(string command)
{
string output = "";
try
{
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = "/c " + command;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
//psi.Verb = "runas";
var cmd = Process.Start(psi);
output = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
}
catch(Exception ex)
{
}
return output;
}