我正在尝试访问命令行并执行命令,然后将输出返回到我的 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";
看看它是否有效。
关于c# - 从 ASPX 页面运行命令行,并将输出返回到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/247668/