How can my C# code run git commands when it detects changes in tracked file? I am writing a VisualStudio/C# console project for this purpose.
I am new to the the .NET environment and currently working on integrating automated GIT commits to a folder. I need to automatically commit any change/add/delete on a known folder and push that to a git remote. Any guidance appreciated. Thank you.
Here is what I have and the last one is the one I need some guidance with:
Tentative commands the project needs to run:
git add -A git commit "explanations_of_changes" git push our_remote
NOTE: This code (with no user interaction) will be the only entity committing to this repo so I am not worried about conflicts and believe this flow will work.
All you have to do is load Command Prompt (Load the Start menu, then click "Run", type cmd and hit enter), then you can use Git commands as normal.
I realize this is an old question but I wanted to add the solution I recently came across to help those in the future.
The PowerShell
class provides an easy way to interact with git. This is part of the System.Management.Automation
namespace in .NET. Note that System.Management.Automation.dll is available via NuGet.
string directory = ""; // directory of the git repository using (PowerShell powershell = PowerShell.Create()) { // this changes from the user folder that PowerShell starts up with to your git repository powershell.AddScript($"cd {directory}"); powershell.AddScript(@"git init"); powershell.AddScript(@"git add *"); powershell.AddScript(@"git commit -m 'git commit from PowerShell in C#'"); powershell.AddScript(@"git push"); Collection<PSObject> results = powershell.Invoke(); }
In my opinion this is cleaner and nicer than using the Process.Start()
approach. You can modify this to your specfic needs by editing the scripts that are added to the powershell
object.
As commented by @ArtemIllarionov, powershell.Invoke()
does not return errors but the Streams
property has output information. Specifically powerShell.Streams.Error
for errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With