仓库:MuZiCul/GitHelper(原创)· 语言:C# + PowerShell · 定位:解决国内网络环境下 GitHub 连接失败/被重置
Windows 下的交互式 GitHub 网络工具:双击 GitHelper.exe 打开一个带菜单的 PowerShell 控制台窗口,内置针对 GitHub 网络问题的辅助菜单。也可直接当普通 PowerShell 终端用。
适用报错:
fatal: unable to access 'https://github.com/xxx/xxx.git/': Failed to connect to github.com port 443
Program.cs)核心思路:把 PowerShell 脚本作为嵌入资源打包进 C# exe,运行时释放到临时目录再拉起 PowerShell 执行。
private static void Main()
{
string script = ExtractScript(); // 从 exe 资源中提取 init.ps1
if (script == null)
{
MessageBox.Show("未找到内置的 init.ps1 资源,程序可能已损坏。", ...);
return;
}
string tempFile = Path.Combine(Path.GetTempPath(), "GitHelper_init.ps1");
// UTF-8 with BOM,确保 Windows PowerShell 5.1 正确解析中文
File.WriteAllText(tempFile, script, new UTF8Encoding(true));
var psi = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = "-NoExit -NoLogo -ExecutionPolicy Bypass -File \"" + tempFile + "\"",
UseShellExecute = true
};
using (Process p = Process.Start(psi)) { p.WaitForExit(); }
try { File.Delete(tempFile); } catch { } // 退出后清理临时文件
}
三个关键细节:
1. new UTF8Encoding(true) —— 带 BOM 的 UTF-8。Windows PowerShell 5.1 按 GBK 解码无 BOM 的 UTF-8,中文会乱码并导致语法错误。这是中文 Windows 环境的经典坑,作者在 README 里也特别强调了。
2. -ExecutionPolicy Bypass —— 绕过默认禁止脚本执行的策略,无需用户手动改策略。
3. 临时文件 + 退出清理 —— 脚本释放到 %TEMP%,PowerShell 退出后删除,不残留。
private static string ExtractScript()
{
Assembly asm = Assembly.GetExecutingAssembly();
foreach (string res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".init.ps1", StringComparison.OrdinalIgnoreCase))
{
// 读取嵌入资源流
}
}
}
用 Windows 自带的 C# 编译器 csc.exe,无需安装 Visual Studio / .NET SDK:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /nologo /target:winexe `
/out:GitHelper.exe `
/resource:init.ps1,GitHelper.init.ps1 `
/r:System.Windows.Forms.dll /r:System.Drawing.dll Program.cs
/target:winexe —— 无控制台窗口(GUI 模式)/resource:init.ps1,GitHelper.init.ps1 —— 把脚本嵌入为资源| 选项 | 功能 |
|---|---|
1 |
配置代理:自动检测本机常见代理端口(7890、7897、10808、10809 等),一键写入 git 的 GitHub 专用代理配置 |
2 |
配置 SSH 走 443:生成 SSH 密钥(已有则跳过)、写 ~/.ssh/config、可选把 origin 改为 SSH 地址,最后测试连接 |
3 |
测试连通性:TCP 检测 github.com / ssh.github.com / gitee.com 等 5 个目标 |
4 |
清除配置:移除代理/SSH 443 设置(SSH config 自动备份 .bak) |
5 |
重新显示菜单 |
0 |
退出菜单,进入普通 PowerShell 命令模式 |
除菜单项外的任何输入直接作为 PowerShell 命令执行(git push 等)。
~/.gitconfig 与 ~/.ssh/config.bakgit tag v1.0.0
git push origin v1.0.0
# 中文描述写入 UTF-8 的 .md 文件,用 --notes-file 传入避免命令行编码乱码
gh release create v1.0.0 GitHelper/GitHelper.exe --title "GitHelper v1.0.0" --notes-file release_notes.md
这个工具不大,但有几个细节我处理过:
工具虽小,单文件分发、脚本内嵌、编码细节、可逆操作这几点是我在做 Windows 小工具时常用的做法。