C# 使用c获取git命令行返回值#
我想从c#运行git命令。下面是我编写的代码,它确实执行git命令,但我无法捕获返回值。当我从命令行手动运行它时,这就是我得到的输出 当我从程序中运行时,唯一得到的是C# 使用c获取git命令行返回值#,c#,git,C#,Git,我想从c#运行git命令。下面是我编写的代码,它确实执行git命令,但我无法捕获返回值。当我从命令行手动运行它时,这就是我得到的输出 当我从程序中运行时,唯一得到的是 Cloning into 'testrep'... 其余信息未捕获,但命令已成功执行 class Program { static void Main(string[] args) { ProcessStartInfo startInfo = new ProcessStartInfo("git.
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:tk1@localhost/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();
}
}
类程序
{
静态void Main(字符串[]参数)
{
ProcessStartInfo-startInfo=新的ProcessStartInfo(“git.exe”);
startInfo.UseShellExecute=false;
startInfo.WorkingDirectory=@“D:\testrep”;
startInfo.RedirectStandardInput=true;
startInfo.RedirectStandardOutput=true;
startInfo.Arguments=“克隆http://tk1:tk1@localhost/testrep.git”;
流程=新流程();
process.StartInfo=StartInfo;
process.Start();
列表输出=新列表();
字符串lineVal=process.StandardOutput.ReadLine();
while(lineVal!=null)
{
output.Add(lineVal);
lineVal=process.StandardOutput.ReadLine();
}
int val=output.Count();
process.WaitForExit();
}
}
一旦调用process.WaitForExit()
且进程已终止,您只需使用process.ExitCode
即可获得所需的值。从手册页获取:
--进展
默认情况下,当标准错误流附加到时,会在标准错误流上报告进度状态
一个端子,除非指定了-q。此标志强制进度状态,即使标准
错误流未定向到终端
交互运行git clone
时,输出中的最后三行被发送到标准错误,而不是标准输出。但是,当您从程序运行命令时,它们不会显示在那里,因为它不是交互式终端。您可以强制它们出现,但是输出对于程序解析来说没有任何用处(大量的\r
更新进度值)
最好不要解析字符串输出,而是查看git clone
的整数返回值。如果它不是零,则表示您有一个错误(标准错误中可能有一些内容可以显示给用户)。您的代码看起来正常。
这是git的问题
git clone git://git.savannah.gnu.org/wget.git 2> stderr.txt 1> stdout.txt
stderr.txt为空
stdout.txt:
克隆到“wget”
看起来git没有使用标准控制台。write()类似于输出。当它写入百分比时,您可以看到它。它都在一行中,不像:
10%
25%
60%
100%你试过了吗?文档并不完整,但它很容易使用,而且有一个简单的方法。您也可以随时查看以了解用法。简单的克隆如下所示:
string URL = "http://tk1:tk1@localhost/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());
}
process.StandardError.ReadToEnd() + "\n" + process.StandardOutput.ReadToEnd();