2014-09-29 39 views
0

我有一個批處理文件在共享位置,我從.net代碼執行,但批處理文件並沒有執行infact發生的是整個代碼的批處理文件不工作只是部分代碼正在工作。我假設.net代碼執行完成並停止批處理文件的執行。 下面是我的.NET代碼批處理文件不從c#代碼運行

private static void ExecuteCommand(string command, string arguments) 
    { 
     try 
     { 
      Console.WriteLine("Code execution starts"); 
      Console.WriteLine("command: " + command); 
      Console.WriteLine("arguments: " + arguments); 
      var process = new Process(); 

      process.StartInfo.FileName = command; 
      if (!string.IsNullOrEmpty(arguments)) 
      { 
       process.StartInfo.Arguments = arguments; 
      } 

      process.StartInfo.CreateNoWindow = true; 
      process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
      //process.StartInfo.CreateNoWindow = false; 
      //process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 
      process.StartInfo.UseShellExecute = true; 
      process.EnableRaisingEvents = true; 
      //process.StartInfo.RedirectStandardError = true; 
      //process.StartInfo.RedirectStandardOutput = true; 
      string stdError; 
      // process.Start(); 
      Thread.Sleep(60000); 
      ThreadPool.QueueUserWorkItem(delegate 
      { 
       process.Start(); 
       // process.WaitForExit(); 
      }); 
      //Thread.Sleep(60000); 

      //ThreadStart ths = new ThreadStart(delegate() 
      //{ 
      // process.Start(); 
      // //process.BeginOutputReadLine(); 
      // //stdError = process.StandardError.ReadToEnd(); 
      //}); 

      //process.Start(); 

      //process.BeginOutputReadLine(); 
      //stdError = process.StandardError.ReadToEnd(); 

      Console.WriteLine("Code execution ends"); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Code execution error: "+e.Message +"||"+e.InnerException.ToString()); 

     } 
    } 

要求是啓動批處理文件的執行,並做n要等待批處理文件執行的任何輸出或精加工。當我從命令提示符或Windows資源管理器運行批處理文件它工作正常。不能在.net代碼中使用cmd.exe,因爲當批處理文件不存在或許可問題時我們需要處理除法選項

+0

您是否嘗試過在'process.StartInfo'中設置'WorkingDirectory'?檢查停止的批處理文件的執行情況。也許有一定的錯誤。 – JeffRSon 2014-09-29 10:11:15

回答

0

我認爲您可以使用WaitForExit方法而不是使用可能或不可以使用睡眠足夠了。

關於它的更多信息:http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx

如果不工作,你可以使用一種變通方法,比如使用的過程開始之前創建的,並通過它結束時,該批處理刪除的文件,它的檢查定期以FileSystemWatcherhttp://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx)作爲檢查過程是否完成的方式。