我需要一些关于从 C#/ASP.NET Web 应用程序使用命令行实用程序的建议。
我找到了一个用于将文件转换为 CSV 格式的第 3 方实用程序。该实用程序运行良好,可以从命令行使用。
我一直在网上寻找有关如何执行命令行实用程序的示例,并找到了 this示例。
问题是这不是很好。当我尝试使用我的实用程序使用示例代码时,我收到一条提示,要求我在客户端计算机上安装该实用程序。这不是我想要的。我不希望用户看到后台发生了什么。
是否可以在服务器端执行命令并从那里处理文件?
如有任何帮助,我们将不胜感激。
最佳答案
我过去做过几次这样的事情,以下是对我有用的:
创建一个 IHttpHandler 实现(作为 .ashx 文件最容易实现)来处理转换。在处理程序中,使用 System.Diagnostics.Process 和 ProcessStartInfo 运行您的命令行实用程序。您应该能够将标准输出重定向到 HTTP 响应的输出流。这是一些代码:
public class ConvertHandler : IHttpHandler
{
#region IHttpHandler Members
bool IHttpHandler.IsReusable
{
get { return false; }
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
var jobID = Guid.NewGuid();
// retrieve the posted csv file
var csvFile = context.Request.Files["csv"];
// save the file to disk so the CMD line util can access it
var filePath = Path.Combine("csv", String.Format("{0:n}.csv", jobID));
csvFile.SaveAs(filePath);
var psi = new ProcessStartInfo("mycsvutil.exe", String.Format("-file {0}", filePath))
{
WorkingDirectory = Environment.CurrentDirectory,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = psi })
{
// delegate for writing the process output to the response output
Action<Object, DataReceivedEventArgs> dataReceived = ((sender, e) =>
{
if (e.Data != null) // sometimes a random event is received with null data, not sure why - I prefer to leave it out
{
context.Response.Write(e.Data);
context.Response.Write(Environment.NewLine);
context.Response.Flush();
}
});
process.OutputDataReceived += new DataReceivedEventHandler(dataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(dataReceived);
// use text/plain so line breaks and any other whitespace formatting is preserved
context.Response.ContentType = "text/plain";
// start the process and start reading the standard and error outputs
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
// wait for the process to exit
process.WaitForExit();
// an exit code other than 0 generally means an error
if (process.ExitCode != 0)
{
context.Response.StatusCode = 500;
}
}
}
#endregion
}
关于c# - 在 ASP.NET 中执行命令行实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817777/