Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c# - Running Command line from an ASPX page, and returning output to page

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...