c# - 单击链接按钮时运行 "ping"命令

标签 c# asp.net command-line

我试图在单击链接按钮时弹出 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/

相关文章:

linux - 在没有图形环境的 Linux 中运行 Matlab?

java - 通过 java 应用程序使用 git

c# - 如果 abort() 不起作用,强制关闭 'rogue' 线程

c# - System.NotSupportedException 使用已编译的 LINQ 查询

c# - 定义应使用多个节点创建哪个节点索引

c# - Asp.net 自动阻止任何类似于 html 代码的输入

asp.net - 丢失 WebForm 用户控件的状态

c# - 当 id 具有文件扩展名时,ASP.NET MVC 4 路由不起作用

c# - 在 WPF C# 中将 ListView 的项目复制到剪贴板

未找到 Java 包 : Compiling with CPlex from command line