2014年7月17日 星期四

ASP.NET 呼叫CMD執行批次檔BAT

ASP.NET 呼叫CMD執行批次檔BAT

C#:
  1. private void go()
  2. {
  3. try
  4. {
  5. // Get the full file path
  6. string strFilePath = @"C:\inetpub\wwwroot\ga\copyphone.bat";
  7.  
  8. // Create the ProcessInfo object
  9. System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
  10. psi.UseShellExecute = false;
  11. psi.RedirectStandardOutput = true;
  12. psi.RedirectStandardInput = true;
  13. psi.RedirectStandardError = true;
  14. psi.WorkingDirectory = @"C:\inetpub\wwwroot\ga\";
  15.  
  16. // Start the process
  17. System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
  18.  
  19.  
  20. // Open the batch file for reading
  21. System.IO.StreamReader strm = new System.IO.StreamReader(strFilePath, System.Text.Encoding.GetEncoding(950));
  22. //System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
  23. //strm.CurrentEncoding.GetEncoder = System.Text.Encoding.GetEncoding(950);
  24. //strm = System.IO.File.OpenText(strFilePath);
  25. Response.Write(strm.CurrentEncoding.ToString());
  26.  
  27. // Attach the output for reading
  28. System.IO.StreamReader sOut = proc.StandardOutput;
  29.  
  30. // Attach the in for writing
  31. System.IO.StreamWriter sIn = proc.StandardInput;
  32.  
  33.  
  34. // Write each line of the batch file to standard input
  35. while (strm.Peek() != -1)
  36. {
  37. sIn.WriteLine(strm.ReadLine());
  38. }
  39.  
  40. strm.Close();
  41.  
  42. // Exit CMD.EXE
  43. string stEchoFmt = "# {0} run successfully. Exiting";
  44.  
  45. sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
  46. sIn.WriteLine("EXIT");
  47.  
  48. // Close the process
  49. proc.Close();
  50.  
  51. // Read the sOut to a string.
  52. string results = sOut.ReadToEnd().Trim();
  53.  
  54.  
  55. // Close the io Streams;
  56. sIn.Close();
  57. sOut.Close();
  58.  
  59. string fmtStdOut = "{0}";
  60. this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "
  61. ")));
  62. }
  63. catch (Exception ex)
  64. {
  65.  
  66. throw ex;
  67. }
  68. }

沒有留言:

張貼留言