从ASPX页面运行命令行,并将输出返回到页面

我正在尝试访问命令行并执行命令,然后将输出返回到我的aspx页面。 一个很好的例子是在aspx页面的页面加载上运行dir并通过Response.Write()返回输出。 我尝试过使用下面的代码。 当我尝试调试它时,它会运行,但永远不会完成加载,也不会呈现输出。 我正在使用C#和.NET Framework 3.5sp1。 任何帮助非常感谢。

谢谢,布莱恩

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); } } 

您遇到cmd.exe命令行参数的语法问题。 这就是为什么cmd永远不会退出的原因。
为了让cmd.exe运行一个程序然后退出,你需要发送语法“/ c [command]”。 尝试使用该行运行相同的代码

  si.StartInfo.Arguments = "dir"; 

换成了

  si.StartInfo.Arguments = "/c dir"; 

并看看它是否有效。

最有可能的问题是权限问题。 运行ASP.NET进程的用户权限非常有限。

因此,要么必须为该用户设置适当的权限,要么在其他用户下运行ASP.NET。

这隐藏了安全风险,所以你必须非常小心。

这太疯狂了! 使用System.IO名称空间从C#程序中创建文件列表! 这很容易做到; 虽然这种技术也有授权问题。

使用System.Diagnostics.Process。

这是一些shell代码,用于在命令行上运行subversion命令。

  /////////////////////////////////////////////////////////////////////// public static string run_svn(string args_without_password, string svn_username, string svn_password) { // run "svn.exe" and capture its output System.Diagnostics.Process p = new System.Diagnostics.Process(); string svn_path = Util.get_setting("SubversionPathToSvn", "svn"); p.StartInfo.FileName = svn_path; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; args_without_password += " --non-interactive"; Util.write_to_log ("Subversion command:" + svn_path + " " + args_without_password); string args_with_password = args_without_password; if (svn_username != "") { args_with_password += " --username "; args_with_password += svn_username; args_with_password += " --password "; args_with_password += svn_password; } p.StartInfo.Arguments = args_with_password; p.Start(); string stdout = p.StandardOutput.ReadToEnd(); p.WaitForExit(); stdout += p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); if (error != "") { Util.write_to_log(error); Util.write_to_log(stdout); } if (error != "") { string msg = "ERROR:"; msg += "
"; msg += "
Error executing svn.exe command from web server."; msg += "
" + error; msg += "
Arguments passed to svn.exe (except user/password):" + args_without_password; if (error.Contains("File not found")) { msg += "

***** Has this file been deleted or renamed? See the following links:"; msg += "
http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html"; msg += "
http://subversion.open.collab.net/articles/best-practices.html"; msg += "
"; } return msg; } else { return stdout; } }