2012-10-17 18 views
2

我想從c#運行git命令。下面是我編寫的代碼,它確實執行了git命令,但我無法捕獲返回值。當我從命令行手動運行它時,這是我得到的輸出。使用c獲得git命令行返回值#

enter image description here

當我從程序來看,我唯一得到的就是信息沒有捕捉

Cloning into 'testrep'... 

休息,但該命令執行成功。

class Program 
{ 
    static void Main(string[] args) 
    { 
     ProcessStartInfo startInfo = new ProcessStartInfo("git.exe"); 

     startInfo.UseShellExecute = false; 
     startInfo.WorkingDirectory = @"D:\testrep"; 
     startInfo.RedirectStandardInput = true; 
     startInfo.RedirectStandardOutput = true; 
     startInfo.Arguments = "clone http://tk1:[email protected]/testrep.git"; 

     Process process = new Process(); 
     process.StartInfo = startInfo; 
     process.Start(); 

     List<string> output = new List<string>(); 
     string lineVal = process.StandardOutput.ReadLine(); 

     while (lineVal != null) 
     { 

      output.Add(lineVal); 
      lineVal = process.StandardOutput.ReadLine(); 

     } 

     int val = output.Count(); 
     process.WaitForExit(); 

    } 
} 

回答

1

從手冊頁git clone

--progress 進展狀態報告在默認情況下的標準誤差流時它連接到 一個終端,除非指定-q。即使標準的 錯誤流沒有定向到終端,該標誌也會強制執行進度狀態。

交互式運行git clone時,輸出中的最後三行發送到標準錯誤,而不是標準輸出。但是,當您從程序運行命令時,它們不會顯示在那裏,但是,因爲它不是交互式終端。你可以強制它們出現,但是輸出結果不會被程序解析的任何東西所使用(大量的\rs來更新進度值)。

你最好不要解析字符串輸出,而是看看整數返回值git clone。如果它不爲零,則發生錯誤(並且可能會出現標準錯誤,您可以向用戶顯示)。

1

一旦你調用process.WaitForExit()和進程已經終止,你可以簡單地使用process.ExitCode這將讓你你想要的值。

0

您的代碼看起來沒問題。 這是git問題。

git clone git://git.savannah.gnu.org/wget.git 2> stderr.txt 1> stdout.txt 

的stderr.txt是空 stdout.txt: 克隆到 'wget的' ......

它看起來像混帳不使用標準console.write()之類的輸出,你可以看到它時,它寫個這一切都在同一行不喜歡的: 10%

25%

60%

100%

1

你試過libgit2sharp?文檔不完整,但使用非常簡單,並且有一個nuget package。您始終可以查看test code以查看使用情況。一個簡單的克隆會是這樣的:

string URL = "http://tk1:[email protected]/testrep.git"; 
string PATH = @"D:\testrep"; 
Repository.Clone(URL, PATH); 

讀取更改容易,以及:

using (Repository r = new Repository(PATH)) 
{ 
    Remote remote = r.Network.Remotes["origin"]; 
    r.Network.Fetch(remote, new FetchOptions()); 
}