我试图在单击链接按钮时弹出 Windows 命令提示符并运行 ping 命令。链接按钮看起来像:
<asp:LinkButton runat="server" ID="lbFTPIP" OnCommand="lbFTPIP_OnCommand" CommandArgumnet="1.2.3.4" Text="1.2.3.4"/>
我为 OnCommand 尝试过此操作:
protected void lbFTPIP_OnCommand(object sender, CommandEventArgs e)
{
string sFTPIP = e.CommandArgument.ToString();
string sCmdText = @"ping -a " + sFTPIP;
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = sCmdText;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.Start();
}
当我单击链接时,它会打开命令提示符,但不会显示或执行命令,它只显示当前目录。不确定我在这里缺少什么。
它是网页的一部分,如果这有区别的话。
最佳答案
为了打开控制台并立即运行命令,您需要使用 /C
或 /K
开关:
// Will run the command and then close the console.
string sCmdText = @"/C ping -a " + sFTPIP;
// Will run the command and keep the console open.
string sCmdText = @"/K ping -a " + sFTPIP;
如果您想设置“按任意键”,您可以添加PAUSE
:
// Will run the command, wait for the user press a key, and then close the console.
string sCmdText = @"/C ping -a " + sFTPIP + " & PAUSE";
编辑:
最好重定向输出,然后单独显示结果:
Process p = new Process();
// No need to use the CMD processor - just call ping directly.
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = "-a " + sFTPIP;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
var output = p.StandardOutput.ReadToEnd();
// Do something the output.
关于c# - 单击链接按钮时运行 "ping"命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160844/