我试图在命令提示符下在C#页面上执行.aspx代码中的命令。代码不会抛出任何错误,但是命令不会执行,因为没有生成新文件。
我没有看到命令本身有任何问题,因为如果我从调试视图复制命令并将其粘贴到命令提示符中,它就会执行得很好。
知道为什么我的代码不生成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.发布于 2015-08-28 16:42:16
假设您想继续在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 = 18mshttps://stackoverflow.com/questions/32275726
复制相似问题