从ActionResult中运行Exe

本文关键字:Exe 运行 ActionResult | 更新日期: 2023-09-27 18:03:14

我正试图将doc转换为html,这是我使用的代码。问题是,我没有例外,但我没有创建文件。我已经尝试了各种替代方法,但不知道如何进行。

[HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        //check if file is ok
        if (file != null && file.ContentLength > 0)
        {
            var path = Path.Combine(Server.MapPath("~/App_Data/"),
                                    System.IO.Path.GetFileName(file.FileName));
            file.SaveAs(path);
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = ("soffice.exe");
            psi.Arguments = string.Format("--headless --convert-to htm:HTML --outdir " + Server.MapPath("~/App_Data/batch/") + " '"{0}'"", path);
            psi.UseShellExecute = false;
            Process proc = new Process();
            proc.StartInfo = psi;
            proc.Start();
            proc.WaitForExit();
        }
        return View();
    }

我更新了代码:

[HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        //check if file is ok
        if (file != null && file.ContentLength > 0)
        {
            var path = Path.Combine(Server.MapPath("~/App_Data/"),
                                    System.IO.Path.GetFileName(file.FileName));
            file.SaveAs(path);
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = Path.Combine(Server.MapPath("~/App_Data/LOP/App/libreoffice/program/"), "soffice.exe");
            psi.Arguments = string.Format("--headless --convert-to htm:HTML --outdir " + Server.MapPath("~/App_Data/batch/") + " '"{0}'"", path);
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            Process proc = new Process();
            proc.StartInfo = psi;
            proc.Start();
           string myString = proc.StandardOutput.ReadToEnd();
            Console.WriteLine(myString);
            proc.WaitForExit();
            var exitCode = proc.ExitCode;
        }
        return View();
    }

但是Exitcode仍然为0,myString为空:(

——解决方案所有代码都没问题!libreoffice的一个进程被挂在内存中,然后每个其他请求追加而没有给出结果,奇怪的是libreoffice继续给内存中的所有进程exitcode 0

从ActionResult中运行Exe

您可以在进程退出后查询进程实例上的ExitCode属性,以检查进程是否没有错误地执行,或者您可以从StandardOutput属性中读取控制台中发生的事情(但是确保将ProcessStartInfo.RedirectStandardOutput设置为true, ProcessStartInfo.UseShellExecute设置为false,因为MSDN上建议设置为http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.process.standardoutput)。

通过获得流程的输出,可以更好地理解问题的答案。在"psi"变量上,在调用"proc.Start()"之前设置"RedirectStandardOutput = true",然后为了访问输出,添加如下所示的行,并在其上设置一个断点(或其后的行)。

string output = proc.StandardOutput.ReadToEnd();

欲了解更多信息,请查看下面的现有帖子,查看已接受的答案;-)

捕获控制台输出