2019年5月23日 星期四

利用 .NET Standard 函式庫 的 C# 取得 Git 版本號



這邊遇到找不到 Git 的環境變數
所以在 @"Git\cmd" 做了一些修改
這邊得看看你 Git 的執行檔在那個目錄內
再做調整與修改

  1. public class CommitID
  2. {
  3. private static string EnvironmentVariable
  4. {
  5. get
  6. {
  7. string sPath = Environment.GetEnvironmentVariable("Path");
  8. var result = sPath.Split(';');
  9. for (int i = 0; i result.Length; i++)
  10. {
  11. if (result[i].Contains(@"Git\cmd"))
  12. {
  13. sPath = result[i];
  14. }
  15. }
  16. return sPath;
  17. }
  18. }
  19. public static void GetCommitID()
  20. {
  21. string gitPath = System.IO.Path.Combine(EnvironmentVariable, "git.exe");
  22. Console.WriteLine($"環境路徑:{gitPath}");
  23. Process p = new Process();
  24. p.StartInfo.FileName = gitPath;
  25. p.StartInfo.Arguments = "rev-parse HEAD";
  26. p.StartInfo.CreateNoWindow = true;
  27. p.StartInfo.UseShellExecute = false;
  28. p.StartInfo.RedirectStandardOutput = true;
  29. p.OutputDataReceived += OnOutputDataReceived;
  30. p.Start();
  31. p.BeginOutputReadLine();
  32. p.WaitForExit();
  33. }
  34. private static void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
  35. {
  36. if (e != null && !string.IsNullOrEmpty(e.Data))
  37. {
  38. ID = e.Data;
  39. Console.WriteLine(e.Data);
  40. }
  41. }
  42. public static string ID { get; set; } = "";
  43. }

使用方法:
先呼叫 GetCommitID()
之後 ID 就會有 Git 的版本號
他會取得目前執行目錄上的 Git 版本號


























沒有留言:

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD