简体   繁体   中英

Execute Console Application with parameters from MVC 5 Controller

I have a MVC 5 controller and a C# console application executed like this:

lp c:\excel.xls /xls

I need to execute this line after I uploaded an XLS file using a Form:

    [HttpPost, ValidateAntiForgeryToken]
    public virtual JsonResult UploadXLS(HttpPostedFileBase XLSFile)
    {
        var uploadDir = Server.MapPath("~/App_Data/");

        if (XLSFile != null)
        {
            var originalFileExtension = Path.GetExtension(XLSFile.FileName);
            var fileName = Guid.NewGuid().ToString() + originalFileExtension;
            var filePath = Path.Combine(uploadDir, fileName);

            XLSFilePartners.SaveAs(filePath);

            // EXECUTE THE CONSOLE PROJECT HERE

            return Json("Uploaded!", "text/html");
        }

        return Json("No File!", "text/html");
    }

To run a program, you can use Process.Start . You will need to supply the path to the executable and the parameters:

Process.Start("lp.exe", "c:\\excel.xls /xls");

If your command line arguments contain spaces (like the file path), you will need to enclose them in quotation marks (and escape those, since it is a string). Like this:

"\"c:\\path with spaces\\excel.xls\" /xls"

Note that this will only start the process - it doesn't wait until it's finished. If you need that, look at Process.WaitForExit .

For more info look at the MSDN page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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