有没有办法使用.NET应用程序使用git?

cnd*_*cnd 63 .net c# git

如何从GitHub 拉出(也可能)一些文件夹?

我的意思是我需要用于.NET的API才能在C#中访问,而不是GUI用于git.

Pok*_*Pok 48

然而,我所做的是编写一个简单的类库,通过运行子进程来调用git命令.

首先,为某些配置创建ProcessStartInfo.

ProcessStartInfo gitInfo = new ProcessStartInfo();
gitInfo.CreateNoWindow = true;
gitInfo.RedirectStandardError = true;
gitInfo.RedirectStandardOutput = true;
gitInfo.FileName = YOUR_GIT_INSTALLED_DIRECTORY + @"\bin\git.exe";
Run Code Online (Sandbox Code Playgroud)

然后创建一个Process来实际运行该命令.

Process gitProcess = new Process();
gitInfo.Arguments = YOUR_GIT_COMMAND; // such as "fetch orign"
gitInfo.WorkingDirectory = YOUR_GIT_REPOSITORY_PATH;

gitProcess.StartInfo = gitInfo;
gitProcess.Start();

string stderr_str = gitProcess.StandardError.ReadToEnd();  // pick up STDERR
string stdout_str = gitProcess.StandardOutput.ReadToEnd(); // pick up STDOUT

gitProcess.WaitForExit();
gitProcess.Close();
Run Code Online (Sandbox Code Playgroud)

然后由您自己调用任何命令.

  • 我必须添加以下行,以便编译器对此类感到满意:gitInfo.UseShellExecute = false; (15认同)
  • 不要同步读出错误流(WaitForExit之前的行).如果两者都有任何数据,它将会死锁. (7认同)
  • 这不会与ssh发生问题,因为没有ssh-agent提供拉动和推送的键吗? (5认同)
  • 请参阅[此答案](http://stackoverflow.com/a/4587739/173497) 的问题 [How to capture Shell command output in C#?](http://stackoverflow.com/questions/4587415/how-to -capture-shell-command-output-in-c) 有关如何捕获标准错误和标准输出的详细信息;如果标准错误的输出大于相关缓冲区,这显然会失败。 (2认同)

Ken*_*itt 40

正如James Manning在当前接受的答案中的评论中所提到的,库libgit2sharp是一个积极支持的项目,为Git提供.NET API.

  • 截至 2020 年 1 月,lib2git 仍然[不处理 Windows 上的长路径](https://github.com/libgit2/libgit2/issues/3053)。如果这是一个问题,你只需要使用 git for windows 即可。 (4认同)
  • **合并**现在由LibGit2Sharp公开;-)(见**[#608](https://github.com/libgit2/libgit2sharp/pull/608)**) (3认同)
  • 这应该是KickStarter. (3认同)
  • @KennyEvitt LibGit2Sharp和LibGit2Sharp-SSH是两个不同的库 - 后者是LibGit2Sharp的一个分支,缺乏官方支持,已经破坏了Nuget包,并且通常是一个"离网"库.使用低级别的非托管代码时,除非您有使用Native功能的经验,否则您要求离开网格时出现问题(内存泄漏,异常处理不当). (2认同)

Dan*_*ite 29

我刚刚发现了这个:http://www.eqqon.com/index.php/GitSharp

GitSharp是Dot.Net Framework和Mono 的Git实现.它旨在与原始Git完全兼容,并且应该是一个轻量级的库,用于基于Git作为其对象数据库或以某种方式读取或操作存储库的酷应用程序......

  • 正如在该页面上提到的,他们已经停止开发,因为libgit2sharp看起来更有前途 - https://github.com/libgit2/libgit2sharp/ (26认同)
  • @RussellGiddings事情发生了一些变化:Merge,Pull,Revert,......现在暴露;-) (3认同)
  • 如今,libgit2sharp 是更好的选择 - 请参阅下面的答案。 (2认同)