2014-01-13 72 views
0

我有一個批處理文件,如果我在命令提示符下輸入此命令,那麼它將完美運行。C#控制檯應用程序無法運行批處理文件,但批處理文件在命令提示符下正常工作

C:\app> C:\app\Process.bat C:\app\files\uploads c:\app\files file2 <- WORKS 

所以只有3個輸入參數。

C:\app\files\uploads : the folder location of input files 
c:\app\files   : the output folder 
file2    : output file name 

如果我運行從C批處理文件:\ app文件夾我看到了輸出文件 我想的過程中從中將安排工作 但運行在Visual Studio調試模式或點擊一個控制檯應用程序自動化exe文件什麼都不做。 我也沒有得到任何異常。

什麼可能是錯誤的 - 權限或其他事情我做錯了?

這是C#代碼

這裏
static void Main(string[] args) 
     { 
      RunBatchFile(@"C:\app\Process.bat", @"C:\app\files\uploads c:\app\files 123456"); 
     } 

public static string RunBatchFile(string fullPathToBatch, string args) 
     {    
      using (var proc = new Process 
      { 
       StartInfo = 
       { 
        Arguments = args,      
        FileName = fullPathToBatch, 

        UseShellExecute = false, 
        CreateNoWindow = true, 
        RedirectStandardOutput = false, 
        RedirectStandardError = false 
       } 
      }) 
      { 
       try 
       { 
        proc.Start(); 
       } 
       catch (Win32Exception e) 
       { 
        if (e.NativeErrorCode == 2) 
        { 
         return "File not found exception"; 
        } 
        else if (e.NativeErrorCode == 5) 
        { 
         return "Access Denied Exception"; 
        } 
       } 
      } 

      return "OK"; 
     } 

回答

1

2個問題:

第一個問題是您需要執行CMD.EXE不是批處理文件。
其次,您正在執行它,但您需要等待該過程完成。你的應用程序是父進程,因爲你沒有等待子進程沒有完成。

您需要發出一個WaitForExit():

var process = Process.Start(...); 
process.WaitForExit(); 

這裏是你想要做什麼:

static void ExecuteCommand(string command) 
{ 
    int exitCode; 
    ProcessStartInfo processInfo; 
    Process process; 

    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command); 
    processInfo.CreateNoWindow = true; 
    processInfo.UseShellExecute = false; 
    process = Process.Start(processInfo); 
    process.WaitForExit(); 
    exitCode = process.ExitCode; 
    process.Close(); 
} 

要運行的批處理文件這樣做從main():

ExecuteCommand("C:\app\Process.bat C:\app\files\uploads c:\app\files file2"); 
+0

你說我不能從C#代碼運行xyz.bat文件?聽起來很奇怪 – kheya

+0

不行,一個批處理文件運行在cmd.exe的進程裏面 –

+0

這個批處理文件有點複雜。我必須找到一個按名稱調用它的解決方案,而不是直接傳遞大的複雜命令。 – kheya

相關問題