我正在尝试在.aspx页面上的C#代码中的命令提示符中执行命令。代码不会抛出任何错误,但是,由于未生成新文件,因此命令不会执行。
我没有看到命令本身的任何问题,因为如果我从调试视图中复制命令并将其粘贴到命令提示符中,它就会正常执行。
为什么我的代码没有生成ResultadoCheckMac_100939.txt的任何想法?
代码:
string cmd = ejecutable_CheckMac + " " + archivo_temporal + " > " + archivo_resultado;
System.Diagnostics.Debugger.Log(0, null, "cmd: " + cmd);
System.Diagnostics.Debugger.Log(0, null, "Start cmd execution.");
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = cmd;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
System.Diagnostics.Debugger.Log(0, null, "Cmd execution finished.");
调试视图输出:
00000014 0.00096980 [136] cmd: C:\inetpub\wwwroot\cgi-bin\tbk_check_mac.exe C:\inetpub\wwwroot\cgi-bin\log\DatosParaCheckMac_100939.txt > C:\inetpub\wwwroot\cgi-bin\log\ResultadoCheckMac_100939.txt
00000015 0.00103170 [136] Start cmd execution.
00000016 0.01946740 [136] Cmd execution finished.
答案 0 :(得分:2)
假设您要继续针对cmd提示执行它,您可以执行以下操作:
var psi = new ProcessStartInfo("cmd", "/c " + cmd); // note the /c
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
Process.Start(psi);
/c
指示提示“执行以下字符串”。但是,更简洁的方法可能是拦截输出并自己捕获:
var psi = new ProcessStartInfo(ejecutable_CheckMac, archivo_temporal);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
using (var proc = Process.Start(psi))
{
using (StreamReader sr = proc.StandardOutput)
{
// This effectively becomes the intended contents
// of `archivo_resultado`
var summary = sr.ReadToEnd();
}
}
如果我想ping -n 1 8.8.8.8
,我可以使用以下任意一种方式:
// Execute ping against command prompt
var psi = new ProcessStartInfo("cmd", @"/c ping -n 1 8.8.8.8 > save\to\ping.txt");
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
或者,我可以这样做:
// Call ping directly passing parameters and redirecting output
var psi = new ProcessStartInfo("ping", "-n 1 8.8.8.8");
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
using (var proc = Process.Start(psi))
{
using (StreamReader sr = proc.StandardOutput)
{
Console.WriteLine(sr.ReadToEnd());
}
}
两者最终都给了我(大致)相同的输出,现在我不必追逐文件。
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=18ms TTL=54
Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 18ms, Maximum = 18ms, Average = 18ms