2016-10-21 54 views
0

我有一個簡單的批處理文件:運行批處理文件XCOPY並得到結果

xcopy source1 dest1 
xcopy source2 dest2 

我想從.NET應用程序運行它,並獲得過程的結果(據我所知xcopy在成功時返回0,在失敗時返回1),以檢查它是否成功(兩個文件都被複制)。我怎樣才能做到這一點?

感謝

+0

仍然是一個非常基本的問題:)我的意思是我相信谷歌有答案,並有很多關於這個答案。 –

+0

[系統()到C#可能重複,而不需要調用cmd.exe](http://stackoverflow.com/questions/2794386/system-to-c-sharp-without-calling-cmd-exe) –

+1

更好的複製將是http://stackoverflow.com/questions/4251694/how-to-start-a-external-executable-from-c-sharp-and-get-the-exit-code-when-the-p(因爲這實際上顯示如何獲得退出代碼) – sgmoore

回答

2

有這

  1. 三個問題如何執行外部命令的
  2. 如何接收輸出
  3. 如何解析結果

1:運行DOS - 命令很簡單:

System.Diagnostics.Process.Start("xcopy","source1 dest1"); 

2:現在您有兩種可能性來檢索輸出。首先是將命令更改爲「xcopy source1 dest1 >output.txt」,然後讀取txt文件。二是不同運行線程:

var proc = new Process { 
    StartInfo = new ProcessStartInfo { 
     FileName = "xcopy", 
     Arguments = "source1 dest1", 
     RedirectStandardOutput = true 
    } 
}; 
proc.Start(); 
string response=string.Empty; 
while (!proc.StandardOutput.EndOfStream) { 
    response += proc.StandardOutput.ReadLine(); 
} 

現在response包含您的複製命令的響應。現在你所要做的就是解析返回值(3)。

如果您在最後一部分遇到問題,請在SO上搜索或爲其寫一個新問題。

+0

感謝它是偉大的,但while循環永遠不會停止對我:\ –

+1

這是一個「文件已存在」的問題。現在,它的工作,再次感謝! –

+0

如果你想要的只是ExitCode,看起來過於複雜。 – sgmoore