2010-08-13 53 views
0

我有一個c#應用程序寫入批處理文件並執行它。要啓動的應用程序和應用程序的路徑將被寫入批處理文件並執行。這工作正常。如何確保批處理文件通過CMD從c#applicaiton正確執行?

如何確保應用程序通過我的批處理文件在命令提示符下運行成功啓動?

執行批處理文件後,cmd是否返回任何值?或任何其他想法,請...

代碼,我現在使用:

 public void Execute() 
    { 
      string LatestFileName = GetLastWrittenBatchFile(); 
      if (System.IO.File.Exists(BatchPath + LatestFileName)) 
      { 
       System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe"); 
       procinfo.UseShellExecute = false; 
       procinfo.RedirectStandardError = true; 
       procinfo.RedirectStandardInput = true; 
       procinfo.RedirectStandardOutput = true; 

       System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo); 

       System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName); 
       System.IO.StreamReader sroutput = process.StandardOutput; 
       System.IO.StreamWriter srinput = process.StandardInput; 

       while (stream.Peek() != -1) 
       { 
        srinput.WriteLine(stream.ReadLine()); 
       } 

       stream.Close(); 
       process.Close(); 
       srinput.Close(); 
       sroutput.Close(); 
      } 
      else 
      { 
       ExceptionHandler.writeToLogFile("File not found"); 
      } 
    } 

回答

0
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename); 
        psi.RedirectStandardOutput = true; 
        psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
        psi.UseShellExecute = false; 
        System.Diagnostics.Process listFiles; 
        listFiles = System.Diagnostics.Process.Start(psi); 
        System.IO.StreamReader myOutput = listFiles.StandardOutput; 
        listFiles.WaitForExit(2000); 
        if (listFiles.HasExited) 
        { 
         string output = myOutput.ReadToEnd(); 
         MessageBox.Show(output); 
        } 
0

我不熟悉的批處理文件,但如果有可能從它返回退出代碼,你可以檢查一下與System.Diagnostics.Process.ExitCode

0
Process process = Process.Start(new ProcessStartInfo{ 
    FileName = "cmd.exe", 
    Arguments = "/C myfile.bat", 
    UseShellExecute = false, 
}); 
process.WaitForExit(); 
Console.WriteLine("returned {0}", process.ExitCode); 
相關問題