c# - 在 ASP.NET 中执行命令行实用程序

标签 c# .net asp.net

我需要一些关于从 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/

相关文章:

c# - 如何在 C# 中使用反射找到所有实现通用抽象类的类?

c# - 将对象列表添加到实体数据库

c# - Socket.io res 没有得到统一

c# - "throw new NotImplementedException();"到底做了什么?

asp.net - 母版页代码未编译成程序集

c# - 我的辅助方法是否应该在 C# 中使用静态类

.NET 在 Server 2008 中永久缓存 DNS

.net - 2 个项目是否可以引用同一程序集的 2 个不同版本,一个来自 GAC,另一个来自 aap\bin 文件夹?

asp.net - Web.Config 问题

javascript - ASP MVC 将数组对象发送到 JavaScript 函数