I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered. I am using C# and .NET Framework 3.5sp1. Any help much appreciated.
Thanks, Bryan
public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = @"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line
si.StartInfo.Arguments = "dir";
replaced with
si.StartInfo.Arguments = "/c dir";
and see if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With