需求:使用C#代码将共享路径下的数据库脚本提交至GitHub仓库
用C#提交共享路径下的数据库脚本到GitHub仓库
可以使用LibGit2Sharp库实现需求,它是.NET生态中成熟的Git操作类库,能便捷完成克隆、暂存、提交、推送等全流程操作。
步骤1:安装依赖
先通过NuGet安装LibGit2Sharp包:
dotnet add package LibGit2Sharp
也可在Visual Studio的NuGet包管理器中搜索安装。
步骤2:完整实现代码
using System; using System.IO; using LibGit2Sharp; public class DbScriptGitSync { /// <summary> /// 将共享路径下的数据库脚本提交到GitHub仓库 /// </summary> /// <param name="sharedScriptPath">共享路径(存储脚本的目录)</param> /// <param name="localRepoPath">本地仓库的存储路径</param> /// <param name="remoteRepoUrl">GitHub远程仓库地址</param> /// <param name="commitMessage">提交备注</param> /// <param name="gitUsername">GitHub用户名</param> /// <param name="gitToken">GitHub个人访问令牌(PAT)</param> public static void CommitAndPushScripts(string sharedScriptPath, string localRepoPath, string remoteRepoUrl, string commitMessage, string gitUsername, string gitToken) { try { // 1. 克隆远程仓库到本地(若本地仓库不存在) if (!Directory.Exists(localRepoPath)) { Console.WriteLine("正在克隆远程仓库..."); Repository.Clone(remoteRepoUrl, localRepoPath, new CloneOptions { CredentialsProvider = (url, _, __) => new UsernamePasswordCredentials { Username = gitUsername, Password = gitToken } }); } // 2. 复制共享路径下的脚本到本地仓库指定目录 string targetDir = Path.Combine(localRepoPath, "DatabaseScripts"); Directory.CreateDirectory(targetDir); foreach (var scriptFile in Directory.GetFiles(sharedScriptPath, "*.sql", SearchOption.TopDirectoryOnly)) { string destPath = Path.Combine(targetDir, Path.GetFileName(scriptFile)); File.Copy(scriptFile, destPath, overwrite: true); Console.WriteLine($"已同步脚本:{Path.GetFileName(scriptFile)}"); } // 3. 执行Git提交与推送 using (var repo = new Repository(localRepoPath)) { // 暂存所有变更文件 Commands.Stage(repo, "*"); // 跳过空提交 var status = repo.RetrieveStatus(); if (!status.IsDirty) { Console.WriteLine("无需要提交的变更"); return; } // 创建提交记录 var signature = new Signature(gitUsername, $"{gitUsername}@users.noreply.github.com", DateTimeOffset.Now); repo.Commit(commitMessage, signature, signature); Console.WriteLine($"提交完成:{commitMessage}"); // 推送到远程仓库 var pushOpts = new PushOptions { CredentialsProvider = (url, _, __) => new UsernamePasswordCredentials { Username = gitUsername, Password = gitToken } }; repo.Network.Push(repo.Branches["main"], pushOpts); // 若仓库默认分支是master,替换为master Console.WriteLine("已推送到GitHub远程仓库"); } } catch (Exception ex) { Console.WriteLine($"操作失败:{ex.Message}"); throw; } } // 调用示例 public static void Main() { // 替换为实际参数 string sharedPath = @"\\your-share-server\db-scripts"; string localRepoDir = @"D:\LocalRepos\DbScriptRepo"; string remoteUrl = "https://github.com/your-username/your-db-repo.git"; string commitNote = "更新:新增订单表初始化脚本"; string gitUser = "your-github-name"; string gitToken = "your-personal-access-token"; CommitAndPushScripts(sharedPath, localRepoDir, remoteUrl, commitNote, gitUser, gitToken); } }
关键细节说明
- 凭据安全:使用GitHub个人访问令牌(PAT)替代账号密码,避免明文密码泄露,需确保令牌拥有仓库的读写权限。
- 分支适配:代码默认推送
main分支,若你的仓库默认分支是master,需修改对应分支名称。 - 目录自定义:示例中将脚本同步到仓库的
DatabaseScripts目录,可根据实际仓库结构调整目标路径。 - 空提交规避:提交前检查仓库状态,避免无变更时的无效提交。
内容的提问来源于stack exchange,提问作者PDP
相关产品推荐
相关产品推荐

