【问题标题】:Running a batch file from an ASP.Net page从 ASP.Net 页面运行批处理文件
【发布时间】:2012-11-24 17:57:10
【问题描述】:

我试图通过 ASP.Net 页面在服务器上运行批处理文件,这让我发疯。当我运行下面的代码时,什么都没有发生 - 我可以从一些日志语句中看到该代码运行,但我传递给函数的 .bat 文件从未运行。

谁能告诉我我做错了什么?

public void ExecuteCommand(string batchFileLocation)
{
   Process p = new Process();

   // Create secure password
   string prePassword = "myadminpwd";
   SecureString passwordSecure = new SecureString();
   char[] passwordChars = prePassword.ToCharArray();
   foreach (char c in passwordChars)
   {
       passwordSecure.AppendChar(c);
   }

   // Set up the parameters to the process
   p.StartInfo.FileName = @"C:\\Windows\\System32\cmd.exe";
   p.StartInfo.Arguments = @" /C " + batchFileLocation;
   p.StartInfo.LoadUserProfile = true;
   p.StartInfo.UserName = "admin";
   p.StartInfo.Password = passwordSecure;
   p.StartInfo.UseShellExecute = false;
   p.StartInfo.CreateNoWindow = true;

   // Run the process and wait for it to complete
   p.Start();
   p.WaitForExit();
}

在服务器上的“应用程序”事件查看器日志中,每次我尝试运行它时,似乎都会出现以下问题:

错误应用程序 cmd.exe,版本 6.0.6001.18000,时间戳 0x47918bde,错误模块 kernel32.dll,版本 6.0.6001.18000,时间戳 0x4791a7a6,异常代码 0xc0000142,错误偏移量 0x00009cac,进程 id 0x47bc,应用程序启动时间 0xa678d5408

更新

以下代码运行良好(它运行批处理文件):

Process p = new Process();
p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;

// Run the process and wait for it to complete
p.Start();
p.WaitForExit();

但这不会(当我尝试以特定用户身份运行时):

Process p = new Process();

// Create secure password
string prePassword = "adminpassword";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
      passwordSecure.AppendChar(c);
}

p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;
p.StartInfo.UserName = "admin";
p.StartInfo.Password = passwordSecure;

// Run the process and wait for it to complete
p.Start();
p.WaitForExit();

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    直接调用批处理文件即可:

    p.StartInfo.FileName = batchFileLocation;
    

    另外,确保WorkingDirectory 设置在正确的位置:

    p.StartInfo.WorkingDirectory= Path.GetDirectoryName(batchFileLocation);
    

    【讨论】:

    • 我已经尝试过了,我得到了相同的结果。代码似乎运行正常,但批处理文件永远不会启动。
    • @Jimmy - 你检查过传入的参数吗?是否正确,文件在传入的位置?
    • 是的,我已将参数放入日志文件以检查是否正常,并检查了实际文件是否存在。
    • 我现在也设置了。无论我使用什么代码(使用 cmd.exe 或直接调用批处理文件),似乎都会发生错误 - 我已将其添加到我的问题中 - 我在服务器上事件查看器的“应用程序”日志下看到了这个。
    • @Jimmy - 网站是否在有权运行此批处理文件和 cmd.exe 的帐户下运行?
    【解决方案2】:

    “错误应用程序 cmd.exe”上的小 google 将我指向这个 IIS forum

    在IIS下好像不能在后台新建进程,除非你使用CreateProcessWithLogon方法。 (我没有测试过)。

    【讨论】:

    • 这看起来像我看到的问题 - 不幸的是,来自 IIS 论坛主题的解决方案链接似乎已关闭。
    猜你喜欢
    • 1970-01-01
    • 2012-12-18
    • 2011-10-29
    • 2012-08-07
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 2012-09-21
    相关资源
    最近更新 更多