繁体   English   中英

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

[英]Execute a command line utility in ASP.NET

我需要一些关于使用C#/ ASP.NET Web应用程序中的命令行实用程序的建议。

我找到了第三方实用程序,用于将文件转换为CSV格式。 该实用程序工作正常,可以从命令行使用。

我一直在网上寻找有关如何执行命令行实用程序的示例,并找到了示例。

问题是这不是很好。 当我尝试使用我的实用程序使用示例代码时,我得到一个提示,要求我在客户端计算机上安装该实用程序。 这不是我想要的。 我不希望用户看到后台发生了什么。

是否可以执行命令服务器端并从那里处理文件?

任何帮助将不胜感激。

我过去曾多次做过类似的事情,这对我有用:

创建一个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
}

该命令正在运行服务器端。 任何代码都在服务器上运行。 您提供的示例中的代码可以正常工作。 您只需确保在服务器上正确设置了该实用程序,并且您具有该目录/文件的权限。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM