// Base64编解码 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:文本⇆Base64(标准/URL-safe,容错解码);任意文件→Base64/Data URI(批量); // Base64→文件还原(自动剥离 data URI 头)。大文件、隐私内容离线处理,不经过浏览器。 // 边界:单文件上限 256MB(内存所限);解码严格校验字符集,报错带位置。 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class B64Ops { public const long MaxFileBytes = 256L * 1024 * 1024; // 256MB public const int WrapWidth = 76; // MIME 惯例,记事本友好 /* 文本 → Base64(UTF-8)。urlSafe:+→- /→/ 改 _、去 = */ public static string EncodeText(string text, bool urlSafe) { string b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(text ?? "")); return urlSafe ? ToUrlSafe(b64) : b64; } /* Base64 → 文本(UTF-8)。容错:去空白、URL-safe 还原、补 padding */ public static string DecodeText(string b64) { byte[] raw = DecodeBytes(b64); return Encoding.UTF8.GetString(raw); } public static byte[] DecodeBytes(string b64) { string s = NormalizeInput(b64); try { return Convert.FromBase64String(s); } catch (FormatException) { // 再找第一个非法字符的位置,报错说人话 int pos = FirstIllegal(s); if (pos >= 0) throw new FormatException("第 " + (pos + 1) + " 个字符「" + s[pos] + "」不是 Base64 字符(只允许 A-Z a-z 0-9 + / - _ =)"); throw; } } /* 统一输入:去所有空白,URL-safe 字母表还原,自动补齐 padding */ public static string NormalizeInput(string b64) { if (b64 == null) return ""; StringBuilder sb = new StringBuilder(b64.Length); foreach (char c in b64) { if (char.IsWhiteSpace(c)) continue; if (c == '-') { sb.Append('+'); continue; } if (c == '_') { sb.Append('/'); continue; } sb.Append(c); } string s = sb.ToString().TrimEnd('='); int pad = (4 - s.Length % 4) % 4; // 长度 %4==1 无法构成合法 Base64(哪怕补齐),交由 Convert 报错 return s + new string('=', pad); } private static int FirstIllegal(string s) { for (int i = 0; i < s.Length; i++) { char c = s[i]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') continue; return i; } return -1; } public static string ToUrlSafe(string b64) { return b64.Replace('+', '-').Replace('/', '_').TrimEnd('='); } /* 剥离 Data URI 头:data:image/png;base64,xxxx → ("image/png", "xxxx") 没有 data 头的原样返回(mediaType 为 null)。 */ public static string StripDataUri(string s, out string mediaType) { mediaType = null; if (s == null) return ""; string t = s.TrimStart(); if (!t.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) return s; int comma = t.IndexOf(','); if (comma < 0) return s; string head = t.Substring(5, comma - 5); // image/png;base64 int semi = head.IndexOf(';'); mediaType = semi >= 0 ? head.Substring(0, semi) : head; return t.Substring(comma + 1); } public static string MakeDataUri(string mediaType, byte[] raw) { if (string.IsNullOrEmpty(mediaType)) mediaType = "application/octet-stream"; return "data:" + mediaType + ";base64," + Convert.ToBase64String(raw); } /* 按扩展名猜 MIME(常用子集,其余 octet-stream) */ public static string MimeFromExt(string ext) { ext = (ext ?? "").ToLowerInvariant(); switch (ext) { case ".png": return "image/png"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".gif": return "image/gif"; case ".webp": return "image/webp"; case ".svg": return "image/svg+xml"; case ".ico": return "image/x-icon"; case ".bmp": return "image/bmp"; case ".pdf": return "application/pdf"; case ".json": return "application/json"; case ".xml": return "application/xml"; case ".html": case ".htm": return "text/html"; case ".css": return "text/css"; case ".js": return "application/javascript"; case ".txt": return "text/plain"; case ".csv": return "text/csv"; case ".zip": return "application/zip"; case ".mp3": return "audio/mpeg"; case ".mp4": return "video/mp4"; case ".woff": return "font/woff"; case ".woff2": return "font/woff2"; default: return "application/octet-stream"; } } /* 文件 → Base64 文本(76 列换行)。超出上限抛异常。 */ public static string EncodeFile(string path) { long len = new FileInfo(path).Length; if (len > MaxFileBytes) throw new IOException("文件 " + Path.GetFileName(path) + " 超过 256MB 上限(" + (len / 1024 / 1024) + "MB),请改用命令行工具"); byte[] raw = File.ReadAllBytes(path); return Wrap64(Convert.ToBase64String(raw)); } public static string Wrap64(string b64) { if (b64.Length <= WrapWidth) return b64; StringBuilder sb = new StringBuilder(b64.Length + b64.Length / WrapWidth * 2 + 2); for (int i = 0; i < b64.Length; i += WrapWidth) { if (i > 0) sb.Append("\r\n"); int n = Math.Min(WrapWidth, b64.Length - i); sb.Append(b64, i, n); } return sb.ToString(); } /* 文件 → Data URI 文本(单行,供 CSS/HTML 直接贴) */ public static string EncodeFileDataUri(string path) { long len = new FileInfo(path).Length; if (len > MaxFileBytes) throw new IOException("文件 " + Path.GetFileName(path) + " 超过 256MB 上限"); byte[] raw = File.ReadAllBytes(path); return MakeDataUri(MimeFromExt(Path.GetExtension(path)), raw); } /* Base64 文本 → 文件。自动剥 data 头,忽略换行空白。 */ public static byte[] DecodeFileContent(string content, out string mediaType) { string body = StripDataUri(content, out mediaType); return DecodeBytes(body); } /* 还原的文件名:xxx.png.b64.txt → xxx.png;xxx.txt → xxx.txt(无后缀线索时加 _还原) */ public static string RestoredName(string b64FileName) { string name = Path.GetFileName(b64FileName); if (name.EndsWith(".b64.txt", StringComparison.OrdinalIgnoreCase)) return name.Substring(0, name.Length - 8); if (name.EndsWith(".datauri.txt", StringComparison.OrdinalIgnoreCase)) return name.Substring(0, name.Length - 12); return Path.GetFileNameWithoutExtension(name) + "_还原" + Path.GetExtension(name); } /* 输出文件名(带后缀),重名自动 (2) */ public static string NextName(string dir, string baseName) { string p = Path.Combine(dir, baseName); int k = 2; string stem = Path.GetFileNameWithoutExtension(baseName); string ext = Path.GetExtension(baseName); while (File.Exists(p)) { p = Path.Combine(dir, stem + " (" + k + ")" + ext); k++; } return p; } } public partial class B64Form : Form { private TabControl tabs; private TextBox txtIn, txtOut, txtFileB64; private CheckBox chkUrlSafe; private Label lblFileStatus, lblRestoreStatus; private bool headless; // 自测标志:不弹对话框 internal void headless_SetForTest() { headless = true; } public B64Form() { InitUi(); } private TextBox MkBox(int x, int y, int w, int h, bool multi) { TextBox t = new TextBox(); t.Location = new Point(x, y); t.Size = new Size(w, h); t.Multiline = multi; if (multi) { t.ScrollBars = ScrollBars.Both; t.WordWrap = false; } this.Controls.Add(t); return t; } private Button MkBtn(string text, int x, int y, int w, EventHandler onClick) { Button b = new Button(); b.Text = text; b.Location = new Point(x, y); b.Size = new Size(w, 32); b.Click += onClick; return b; } private void InitUi() { this.Text = "Base64编解码 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(720, 480); this.MinimumSize = new Size(720, 480); Label lblTitle = new Label(); lblTitle.Text = "文本⇆Base64、文件→Base64/Data URI、Base64→文件还原;内容全程留在本机,不上传任何服务器"; lblTitle.Location = new Point(16, 12); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); tabs = new TabControl(); tabs.Location = new Point(12, 38); tabs.Size = new Size(696, 396); this.Controls.Add(tabs); // ── 页1:文本 ── TabPage tp1 = new TabPage("文本 ⇆ Base64"); tabs.TabPages.Add(tp1); chkUrlSafe = new CheckBox(); chkUrlSafe.Text = "URL-safe(- 和 _ 代替 + 和 /,适合放进网址)"; chkUrlSafe.Location = new Point(12, 10); chkUrlSafe.AutoSize = true; tp1.Controls.Add(chkUrlSafe); Label li = new Label(); li.Text = "输入(文本或 Base64,会自动识别方向)"; li.Location = new Point(12, 36); li.AutoSize = true; tp1.Controls.Add(li); txtIn = new TextBox(); txtIn.Multiline = true; txtIn.ScrollBars = ScrollBars.Both; txtIn.WordWrap = false; txtIn.Location = new Point(12, 58); txtIn.Size = new Size(660, 120); tp1.Controls.Add(txtIn); Button bEnc = new Button(); bEnc.Text = "编码 ↓"; bEnc.Location = new Point(12, 188); bEnc.Size = new Size(110, 32); bEnc.BackColor = Color.FromArgb(0, 145, 88); bEnc.ForeColor = Color.White; bEnc.FlatStyle = FlatStyle.Flat; bEnc.Click += new EventHandler(delegate { EncodeClick(); }); tp1.Controls.Add(bEnc); Button bDec = new Button(); bDec.Text = "解码 ↑"; bDec.Location = new Point(130, 188); bDec.Size = new Size(110, 32); bDec.Click += new EventHandler(delegate { DecodeClick(); }); tp1.Controls.Add(bDec); Button bCopy1 = new Button(); bCopy1.Text = "复制输出"; bCopy1.Location = new Point(260, 188); bCopy1.Size = new Size(100, 32); bCopy1.Click += new EventHandler(delegate { CopyText(txtOut.Text); }); tp1.Controls.Add(bCopy1); Label lo = new Label(); lo.Text = "输出"; lo.Location = new Point(12, 228); lo.AutoSize = true; tp1.Controls.Add(lo); txtOut = new TextBox(); txtOut.Multiline = true; txtOut.ScrollBars = ScrollBars.Both; txtOut.WordWrap = false; txtOut.ReadOnly = true; txtOut.Location = new Point(12, 250); txtOut.Size = new Size(660, 110); tp1.Controls.Add(txtOut); // ── 页2:文件 → Base64 ── TabPage tp2 = new TabPage("文件 → Base64"); tabs.TabPages.Add(tp2); Label l2 = new Label(); l2.Text = "选一个或多个文件(单文件上限 256MB),输出 .b64.txt(76列换行)或单行 Data URI(可直接贴进 CSS/HTML)"; l2.Location = new Point(12, 12); l2.AutoSize = true; tp2.Controls.Add(l2); Button bPick = new Button(); bPick.Text = "选择文件并转换…"; bPick.Location = new Point(12, 46); bPick.Size = new Size(170, 40); bPick.BackColor = Color.FromArgb(0, 145, 88); bPick.ForeColor = Color.White; bPick.FlatStyle = FlatStyle.Flat; bPick.Click += new EventHandler(PickEncodeClick); tp2.Controls.Add(bPick); Button bOpen2 = new Button(); bOpen2.Text = "打开输出文件夹"; bOpen2.Location = new Point(192, 46); bOpen2.Size = new Size(140, 40); bOpen2.Click += new EventHandler(delegate { OpenDir(EncDir()); }); tp2.Controls.Add(bOpen2); lblFileStatus = new Label(); lblFileStatus.Text = "输出保存在「图片\\Base64导出」(独立于其它工具,原文件不动)"; lblFileStatus.Location = new Point(12, 100); lblFileStatus.AutoSize = true; lblFileStatus.ForeColor = Color.FromArgb(120, 130, 124); tp2.Controls.Add(lblFileStatus); txtFileB64 = new TextBox(); txtFileB64.Multiline = true; txtFileB64.ScrollBars = ScrollBars.Both; txtFileB64.WordWrap = false; txtFileB64.ReadOnly = true; txtFileB64.Location = new Point(12, 126); txtFileB64.Size = new Size(660, 220); tp2.Controls.Add(txtFileB64); // ── 页3:Base64 → 文件 ── TabPage tp3 = new TabPage("Base64 → 文件"); tabs.TabPages.Add(tp3); Label l3 = new Label(); l3.Text = "选 .b64.txt / .datauri.txt / 任意含 Base64 的文本文件,还原成原文件;自动识别 data: 头、自动忽略换行"; l3.Location = new Point(12, 12); l3.AutoSize = true; tp3.Controls.Add(l3); Button bRestore = new Button(); bRestore.Text = "选择 Base64 文本文件并还原…"; bRestore.Location = new Point(12, 46); bRestore.Size = new Size(230, 40); bRestore.BackColor = Color.FromArgb(0, 145, 88); bRestore.ForeColor = Color.White; bRestore.FlatStyle = FlatStyle.Flat; bRestore.Click += new EventHandler(PickRestoreClick); tp3.Controls.Add(bRestore); Button bOpen3 = new Button(); bOpen3.Text = "打开输出文件夹"; bOpen3.Location = new Point(252, 46); bOpen3.Size = new Size(140, 40); bOpen3.Click += new EventHandler(delegate { OpenDir(RestoreDir()); }); tp3.Controls.Add(bOpen3); lblRestoreStatus = new Label(); lblRestoreStatus.Text = "还原结果保存在「图片\\Base64还原」,重名自动加序号,绝不覆盖"; lblRestoreStatus.Location = new Point(12, 100); lblRestoreStatus.AutoSize = true; lblRestoreStatus.ForeColor = Color.FromArgb(120, 130, 124); tp3.Controls.Add(lblRestoreStatus); } private void CopyText(string s) { if (headless || string.IsNullOrEmpty(s)) return; try { Clipboard.SetText(s); } catch { } } private void OpenDir(string dir) { if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); System.Diagnostics.Process.Start("explorer.exe", "\"" + dir + "\""); } internal static string EncDir() { string pic = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (string.IsNullOrEmpty(pic) || !Directory.Exists(pic)) pic = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); return Path.Combine(pic, "Base64导出"); } internal static string RestoreDir() { string pic = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (string.IsNullOrEmpty(pic) || !Directory.Exists(pic)) pic = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); return Path.Combine(pic, "Base64还原"); } private void EncodeClick() { try { txtOut.Text = B64Ops.EncodeText(txtIn.Text, chkUrlSafe.Checked); } catch (Exception ex) { ShowErr(ex.Message); } } private void DecodeClick() { try { txtOut.Text = B64Ops.DecodeText(txtIn.Text); } catch (FormatException ex) { ShowErr("解码失败:" + ex.Message); } } private void ShowErr(string msg) { if (headless) throw new InvalidOperationException(msg); MessageBox.Show(msg, "Base64编解码", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void PickEncodeClick(object sender, EventArgs e) { if (headless) return; using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择要转 Base64 的文件(可多选)"; dlg.Multiselect = true; if (dlg.ShowDialog(this) != DialogResult.OK) return; EncodeFiles(dlg.FileNames); } } internal List EncodeFiles(string[] paths) { List outs = new List(); string dir = EncDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); foreach (string path in paths) { string name = Path.GetFileName(path); bool dataUri = !string.IsNullOrEmpty(B64Ops.MimeFromExt(Path.GetExtension(path))) && IsWebAsset(path); string content = dataUri ? B64Ops.EncodeFileDataUri(path) : B64Ops.EncodeFile(path); string baseName = dataUri ? name + ".datauri.txt" : name + ".b64.txt"; string outPath = B64Ops.NextName(dir, baseName); File.WriteAllText(outPath, content, new UTF8Encoding(false)); outs.Add(outPath); } StringBuilder sb = new StringBuilder(); foreach (string o in outs) { sb.AppendLine("已输出:" + o + "(" + new FileInfo(o).Length + " 字节)"); } txtFileB64.Text = sb.ToString().TrimEnd(); lblFileStatus.Text = "共 " + outs.Count + " 个文件,输出在「图片\\Base64导出」,原文件未动。"; return outs; } /* 网页素材(图片/字体)才用 Data URI,其它给纯 Base64 */ private static bool IsWebAsset(string path) { string e = Path.GetExtension(path).ToLowerInvariant(); return e == ".png" || e == ".jpg" || e == ".jpeg" || e == ".gif" || e == ".webp" || e == ".svg" || e == ".ico" || e == ".woff" || e == ".woff2" || e == ".bmp"; } private void PickRestoreClick(object sender, EventArgs e) { if (headless) return; using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择 Base64 文本文件(可多选)"; dlg.Multiselect = true; dlg.Filter = "文本文件 (*.txt;*.b64;*.base64)|*.txt;*.b64;*.base64|所有文件 (*.*)|*.*"; if (dlg.ShowDialog(this) != DialogResult.OK) return; RestoreFiles(dlg.FileNames); } } internal List RestoreFiles(string[] paths) { List outs = new List(); string dir = RestoreDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); foreach (string path in paths) { if (new FileInfo(path).Length > B64Ops.MaxFileBytes * 2) throw new IOException("文件过大,跳过:" + path); string content = File.ReadAllText(path, Encoding.UTF8); string mediaType; byte[] raw = B64Ops.DecodeFileContent(content, out mediaType); string outName = B64Ops.RestoredName(Path.GetFileName(path)); string outPath = B64Ops.NextName(dir, outName); File.WriteAllBytes(outPath, raw); outs.Add(outPath); } StringBuilder sb = new StringBuilder(); foreach (string o in outs) { sb.AppendLine("已还原:" + o + "(" + new FileInfo(o).Length + " 字节)"); } lblRestoreStatus.Text = "共还原 " + outs.Count + " 个文件,输出在「图片\\Base64还原」。"; return outs; } } // ───────────────────────── 自测 ───────────────────────── public static class B64SelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("Base64编解码 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-b64-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 文本编码:RFC 4648 标准向量 Check("RFC4648 foobar", B64Ops.EncodeText("foobar", false), "Zm9vYmFy"); Check("RFC4648 foob", B64Ops.EncodeText("foob", false), "Zm9vYg=="); Check("RFC4648 fooba", B64Ops.EncodeText("fooba", false), "Zm9vYmE="); Check("空串", B64Ops.EncodeText("", false), ""); Check("中文UTF8", B64Ops.EncodeText("绿色工具箱", false), "57u/6Imy5bel5YW3566x"); // URL-safe string us = B64Ops.ToUrlSafe("ab+/="); Check("URL-safe 替换", us, "ab-_"); string enc = B64Ops.EncodeText(" subjects? + /", true); Check("URL-safe 不含 +/=", enc.Contains("+") || enc.Contains("/") || enc.Contains("="), false); // URL-safe 往返 string round = B64Ops.DecodeText(B64Ops.EncodeText("hello world / + 中文 123", true)); Check("URL-safe 往返", round, "hello world / + 中文 123"); // 标准往返(中文 + 符号 + 长文本) string longText = new string('绿', 5000) + "\r\n特殊<>\"'&=+/#$%"; Check("长文本往返", B64Ops.DecodeText(B64Ops.EncodeText(longText, false)), longText); // 容错解码 Check("去空白", B64Ops.DecodeText("Zm9v YmFy\r\n"), "foobar"); Check("URL-safe 输入还原", B64Ops.DecodeText("aGVsbG8"), "hello"); Check("URL-safe 斜杠输入", B64Ops.DecodeText("aGVsbG8/"), "hello?"); Check("缺 padding 补齐", B64Ops.DecodeText("Zm9vYmFy"), "foobar"); // 非法字符报错带位置 bool threw = false; string msg = ""; try { B64Ops.DecodeText("Zm9vYmF*"); } catch (FormatException ex) { threw = true; msg = ex.Message; } Check("非法字符报错", threw, true); Check("报错带位置", msg.Contains("「*」"), true); // Data URI 剥离 string mt; string body = B64Ops.StripDataUri("data:image/png;base64,Zm9vYmFy", out mt); Check("剥 data 头", body, "Zm9vYmFy"); Check("识别 MIME", mt, "image/png"); string body2 = B64Ops.StripDataUri("Zm9vYmFy", out mt); Check("无 data 头原样", body2, "Zm9vYmFy"); Check("无头 MIME 为空", mt, ""); // MakeDataUri + MimeFromExt Check("MIME png", B64Ops.MimeFromExt(".png"), "image/png"); Check("MIME jpg", B64Ops.MimeFromExt(".JPG"), "image/jpeg"); Check("MIME 未知", B64Ops.MimeFromExt(".xyz"), "application/octet-stream"); byte[] sample = Encoding.UTF8.GetBytes("hi"); Check("MakeDataUri", B64Ops.MakeDataUri("image/png", sample), "data:image/png;base64,aGk="); Check("MakeDataUri 默认", B64Ops.MakeDataUri(null, sample), "data:application/octet-stream;base64,aGk="); // 换行:76 列 string longB64 = B64Ops.EncodeText(new string('a', 200), false); string wrapped = B64Ops.Wrap64(longB64); bool okWrap = true; foreach (string line in wrapped.Split(new string[] { "\r\n" }, StringSplitOptions.None)) { if (line.Length > 76) { okWrap = false; break; } } Check("76 列换行", okWrap, true); Check("换行后解码一致", B64Ops.DecodeText(wrapped), new string('a', 200)); // 文件往返:随机二进制(含所有 256 种字节)→ b64 → 还原 → 字节一致 string bin = Path.Combine(baseDir, "rand.bin"); byte[] raw = new byte[4096]; Random rnd = new Random(42); rnd.NextBytes(raw); File.WriteAllBytes(bin, raw); string b64Text = B64Ops.EncodeFile(bin); string b64File = Path.Combine(baseDir, "rand.bin.b64.txt"); File.WriteAllText(b64File, b64Text, new UTF8Encoding(false)); Check("b64 文件名正确", Path.GetFileName(b64File), "rand.bin.b64.txt"); string mt2; byte[] back = B64Ops.DecodeFileContent(File.ReadAllText(b64File, Encoding.UTF8), out mt2); Check("还原字节数", back.Length, 4096); bool same = back.Length == raw.Length; for (int i = 0; i < raw.Length && same; i++) { if (raw[i] != back[i]) same = false; } Check("字节逐一一致", same, true); Check("普通文件无 MIME", mt2, ""); // 图片文件 → Data URI 文件 → 还原 string png = Path.Combine(baseDir, "tiny.png"); File.WriteAllBytes(png, new byte[] { 0x89, 0x50, 0x4E, 0x47 }); string du = B64Ops.EncodeFileDataUri(png); Check("png→data uri", du.StartsWith("data:image/png;base64,"), true); string duFile = Path.Combine(baseDir, "tiny.png.datauri.txt"); File.WriteAllText(duFile, du); string mt3; byte[] back2 = B64Ops.DecodeFileContent(File.ReadAllText(duFile), out mt3); Check("data uri 还原 MIME", mt3, "image/png"); Check("data uri 还原内容", BitConverter.ToString(back2), "89-50-4E-47"); // 还原文件名规则 Check("去 .b64.txt", B64Ops.RestoredName("a.png.b64.txt"), "a.png"); Check("去 .datauri.txt", B64Ops.RestoredName("a.png.datauri.txt"), "a.png"); Check("普通 txt 加标记", B64Ops.RestoredName("code.txt"), "code_还原.txt"); // 重名加 (2) string d2 = Path.Combine(baseDir, "names"); Directory.CreateDirectory(d2); string n1 = B64Ops.NextName(d2, "a.png"); File.WriteAllText(n1, "x"); string n2 = B64Ops.NextName(d2, "a.png"); Check("重名加 (2)", Path.GetFileName(n1) != Path.GetFileName(n2) && Path.GetFileName(n2).Contains("(2)"), true); // 超限拒绝 bool threwBig = false; try { B64Ops.EncodeFile(new FileInfo(bin).FullName); threwBig = false; } catch { threwBig = true; } Check("小文件不误报", threwBig, false); // Form 层:批量转换 + 还原(不弹对话框直接调内部方法) B64Form form = new B64Form(); form.headless_SetForTest(); List encOut = form.EncodeFiles(new string[] { png, bin }); Check("批量转换产物数", encOut.Count, 2); foreach (string o in encOut) Check("产物存在 " + Path.GetFileName(o), File.Exists(o), true); List res = form.RestoreFiles(encOut.ToArray()); Check("批量还原产物数", res.Count, 2); foreach (string o in res) { Check("还原存在 " + Path.GetFileName(o), File.Exists(o), true); Check("还原非空 " + Path.GetFileName(o), new FileInfo(o).Length > 0, true); } form.Dispose(); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-b64.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(B64SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new B64Form()); } } }