简体   繁体   中英

Execute .Bat File in C# ASP.net was not working after I published in IIS

批处理文件属性

This is my current Code. But I think the problem was in the IIS because I try this in debug mode and it works, and when I published the bat file won't open.

public  ActionResult Print(int? id)
    {

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Item item =  db.Items.Find(id);
        Origin origin =  db.Origins.Where(x => x.OriginMainID == item.OriginMainID && x.IsActive == true).FirstOrDefault();
        var user =  UserManager.FindById(item.CreatedBy);
        string fileLoc = @"e:\SAMPLE.txt";
        string text = "";
        text += item.PropertyCode + "," + origin.Assignee.LName + " " + origin.Assignee.FName + "," + origin.Assignee.Department.ShortCode + "," + user.LastName + " " + user.FirstName + "," + origin.Assignee.CMID;
        if (System.IO.File.Exists(fileLoc))
        {
            using (StreamWriter sw = new StreamWriter(fileLoc))
            {
                sw.Write(text);
            }
        }
        if (item == null && origin == null)
        {
            return HttpNotFound();
        }

         Process.Start(@"C:\PANDA.bat");
        return RedirectToAction("Index");
    }

Instead of writing Process.Start(@"C:\\PANDA.bat"); Try using the following snippet.

Process proc = new Process();
proc.StartInfo.FileName = @"C:\PANDA.bat";
proc.StartInfo.Verb = "runas";
proc.Start();

proc.StartInfo.Verb = "runas"; This line will execute the code as Administrator on Hosted environment, So it will work on IIS.

Your IIS will work under a special user either the IIS_USRS group or under a specific account used under impersonation. In this case, you need to do following:-

  1. File access to be from a directory and never from root of drive. Only administrator can access a file from root. Probably your user account is admin on your machine so you are not noticing this while running via VS
  2. Set a specific account for your web app, and give execute permissions for that account on the folder containing the batch file. Then in your web.config, setup impersonation and provide that user's account name.

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