简体   繁体   中英

Run "ping" command when link button is clicked

I am trying to pop up a Windows Command prompt and run a ping command when a link button is clicked. Link button looks something like:

<asp:LinkButton runat="server" ID="lbFTPIP" OnCommand="lbFTPIP_OnCommand" CommandArgumnet="1.2.3.4" Text="1.2.3.4"/>

I tried this for 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();
}

When I click the link, it opens the command prompt but does not display or execute the command, it just shows the current directory. Not sure what I am missing here.

It is part of a web page, if this makes a difference.

In order to open a console and immediately run a command, you need to use either the /C or /K switch:

// 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;

If you want to institute a "Press any key", you can add a PAUSE :

// Will run the command, wait for the user press a key, and then close the console.
string sCmdText = @"/C ping -a " + sFTPIP + " & PAUSE";

EDIT:

It would probably be best to redirect your output and then display the results separately:

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.

You don't need to execute cmd.exe, just execute ping.exe instead.

string sCmdText = @"-a " + sFTPIP;
Process p = new Process();
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = sCmdText;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
p.Start();

Also, don't set UseShellExecute = false unless you intend to redirect the output, which I'm surprised you are not doing.

First thing is that you have something strange here CommandArgumnet="1.2.3.4" that is misspelled. The other thing is the /C and a space before ping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM