// 文本对比 - 绿色工具箱 // C# 5.0 语法,零依赖。功能:逐行对比两段文本/两个文件,标出新增、删除、相同, // 可忽略空白与大小写,结果可导出报告。LCS 算法,先掐头去尾再算中段 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class TextDiffForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private static readonly Color COL_DEL = Color.FromArgb(200, 48, 48); // 左独有 = 删除 private static readonly Color COL_ADD = Color.FromArgb(0, 130, 70); // 右独有 = 新增 private TextBox txtLeft, txtRight; private RichTextBox rtResult; private CheckBox chkSpace, chkCase; private Label lblSummary, lblStatus; private Button btnGo, btnCopy, btnSave; public TextDiffForm() { InitUi(); } private void InitUi() { this.Text = "文本对比 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(980, 640); this.MinimumSize = new Size(860, 560); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 14, y = 12; Label l0 = new Label(); l0.Text = "把两个版本分别贴进左右两栏(或点“打开”选文件,可直接拖进来),点对比。红=左边独有,绿=右边独有。"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 26; Label ll = new Label(); ll.Text = "左(原版)"; ll.AutoSize = true; ll.Location = new Point(x, y + 4); this.Controls.Add(ll); Button btnOpenL = MkBtn("打开…", x + 82, y - 2, 70, false, OpenLeftClick); y += 28; txtLeft = new TextBox(); txtLeft.Location = new Point(x, y); txtLeft.Size = new Size(468, 170); txtLeft.Multiline = true; txtLeft.ScrollBars = ScrollBars.Both; txtLeft.WordWrap = false; txtLeft.AcceptsReturn = true; txtLeft.AcceptsTab = true; txtLeft.Font = new Font("Consolas", 10f); this.Controls.Add(txtLeft); txtRight = new TextBox(); txtRight.Location = new Point(x + 484, y); txtRight.Size = new Size(468, 170); txtRight.Multiline = true; txtRight.ScrollBars = ScrollBars.Both; txtRight.WordWrap = false; txtRight.AcceptsReturn = true; txtRight.AcceptsTab = true; txtRight.Font = new Font("Consolas", 10f); this.Controls.Add(txtRight); Label lr = new Label(); lr.Text = "右(新版)"; lr.AutoSize = true; lr.Location = new Point(x + 484, y - 26); this.Controls.Add(lr); y += 180; btnGo = MkBtn("对 比", x, y, 120, true, GoClick); y += 44; rtResult = new RichTextBox(); rtResult.Location = new Point(x, y); rtResult.Size = new Size(952, 290); rtResult.ReadOnly = true; rtResult.WordWrap = false; rtResult.Font = new Font("Consolas", 10f); rtResult.BackColor = Color.White; this.Controls.Add(rtResult); y += 298; lblSummary = new Label(); lblSummary.Text = "还没对比。"; lblSummary.AutoSize = true; lblSummary.Location = new Point(x, y + 4); this.Controls.Add(lblSummary); chkSpace = new CheckBox(); chkSpace.Text = "忽略行首尾空白"; chkSpace.AutoSize = true; chkSpace.Location = new Point(x + 420, y + 2); this.Controls.Add(chkSpace); chkCase = new CheckBox(); chkCase.Text = "忽略大小写"; chkCase.AutoSize = true; chkCase.Location = new Point(x + 566, y + 2); this.Controls.Add(chkCase); btnCopy = MkBtn("复制结果", x + 690, y - 2, 100, false, CopyClick); btnSave = MkBtn("导出报告…", x + 800, y - 2, 100, false, SaveClick); y += 34; lblStatus = new Label(); lblStatus.Text = "纯本地处理,内容不出电脑。支持 txt / 代码 / 日志 / 配置等任何文本。"; lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; lblStatus.Location = new Point(x, y); this.Controls.Add(lblStatus); } private Button MkBtn(string text, int px, int py, int w, bool primary, EventHandler onClick) { Button b = new Button(); b.Text = text; b.Location = new Point(px, py); b.Size = new Size(w, 30); b.FlatStyle = FlatStyle.Flat; if (primary) { b.BackColor = COL_GREEN; b.ForeColor = Color.White; b.FlatAppearance.BorderSize = 0; } else { b.FlatAppearance.BorderColor = COL_GREEN; b.ForeColor = Color.FromArgb(0, 110, 66); } b.Click += onClick; this.Controls.Add(b); return b; } private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void OnDragDrop(object sender, DragEventArgs e) { string[] f = (string[])e.Data.GetData(DataFormats.FileDrop); if (f == null || f.Length == 0) return; txtLeft.Text = ReadFile(f[0]); if (f.Length >= 2) txtRight.Text = ReadFile(f[1]); lblStatus.Text = "已载入 " + (f.Length >= 2 ? "两个文件" : "左栏") + ",点“对比”。"; } private string ReadFile(string p) { byte[] raw = File.ReadAllBytes(p); try { var strict = new UTF8Encoding(false, true); return strict.GetString(raw); } catch { return Encoding.GetEncoding("GBK").GetString(raw); } } private void OpenLeftClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "所有文件 (*.*)|*.*"; d.Title = "打开左栏文件"; if (d.ShowDialog() == DialogResult.OK) { txtLeft.Text = ReadFile(d.FileName); lblStatus.Text = "已载入 " + Path.GetFileName(d.FileName); } } } private void GoClick(object sender, EventArgs e) { List a = SplitLines(txtLeft.Text); List b = SplitLines(txtRight.Text); List diff = Diff(a, b, chkSpace.Checked, chkCase.Checked); rtResult.Clear(); int same = 0, del = 0, add = 0; rtResult.SuspendLayout(); foreach (DiffLine dl in diff) { same += dl.Kind == 0 ? 1 : 0; del += dl.Kind == 1 ? 1 : 0; add += dl.Kind == 2 ? 1 : 0; string prefix = dl.Kind == 0 ? " " : (dl.Kind == 1 ? "- " : "+ "); AppendColored(prefix + dl.Text + "\n", dl.Kind == 0 ? Color.FromArgb(90, 96, 92) : (dl.Kind == 1 ? COL_DEL : COL_ADD), dl.Kind != 0); } rtResult.ResumeLayout(); lblSummary.Text = a.Count + " 行 vs " + b.Count + " 行 → 相同 " + same + ",左边独有 " + del + "(红),右边独有 " + add + "(绿)"; lblSummary.ForeColor = (del + add) == 0 ? COL_GREEN : Color.FromArgb(34, 40, 36); lblStatus.Text = (del + add) == 0 ? "两段内容完全一致。" : "对比完成。"; } private void AppendColored(string text, Color c, bool bold) { rtResult.SelectionStart = rtResult.TextLength; rtResult.SelectionLength = 0; rtResult.SelectionColor = c; rtResult.SelectedText = text; rtResult.SelectionStart = rtResult.TextLength; rtResult.SelectionLength = 0; rtResult.SelectionColor = rtResult.ForeColor; } private void CopyClick(object sender, EventArgs e) { if (rtResult.TextLength == 0) { lblStatus.Text = "还没有结果可复制。"; return; } Clipboard.SetText(rtResult.Text); lblStatus.Text = "已复制到剪贴板。"; } private void SaveClick(object sender, EventArgs e) { if (rtResult.TextLength == 0) { lblStatus.Text = "还没有结果可导出。"; return; } using (SaveFileDialog d = new SaveFileDialog()) { d.Filter = "文本文件 (*.txt)|*.txt"; d.FileName = "对比报告.txt"; if (d.ShowDialog() == DialogResult.OK) { File.WriteAllText(d.FileName, rtResult.Text, new UTF8Encoding(true)); lblStatus.Text = "已保存:" + d.FileName; } } } private static List SplitLines(string s) { List lines = new List(); if (s == null || s.Length == 0) return lines; string[] parts = s.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); // 末尾换行产生的空元素去掉,不算一行 int end = parts.Length; if (end > 0 && parts[end - 1].Length == 0) end--; for (int i = 0; i < end; i++) lines.Add(parts[i]); return lines; } // ===== 核心:LCS 行级对比 ===== public class DiffLine { public int Kind; // 0=相同 1=左独有 2=右独有 public string Text; public DiffLine(int kind, string text) { Kind = kind; Text = text; } } private static string Norm(string s, bool ignoreSpace, bool ignoreCase) { if (ignoreSpace) s = s.Trim(); if (ignoreCase) s = s.ToLower(); return s; } public static List Diff(List a, List b, bool ignoreSpace, bool ignoreCase) { List outList = new List(); int n = a.Count, m = b.Count; // 掐头 int pre = 0; while (pre < n && pre < m && Norm(a[pre], ignoreSpace, ignoreCase) == Norm(b[pre], ignoreSpace, ignoreCase)) pre++; // 去尾 int suf = 0; while (suf < n - pre && suf < m - pre && Norm(a[n - 1 - suf], ignoreSpace, ignoreCase) == Norm(b[m - 1 - suf], ignoreSpace, ignoreCase)) suf++; for (int i = 0; i < pre; i++) outList.Add(new DiffLine(0, a[i])); int na = n - pre - suf, nb = m - pre - suf; List mid = new List(); if (na > 0 || nb > 0) { if ((long)na * nb <= 100000000L) { mid = LcsCore(a, pre, na, b, pre, nb, ignoreSpace, ignoreCase); } else { // 超大差异:整块标记,不做逐行分析 for (int i = 0; i < na; i++) mid.Add(new DiffLine(1, a[pre + i])); for (int j = 0; j < nb; j++) mid.Add(new DiffLine(2, b[pre + j])); mid.Insert(0, new DiffLine(0, "……(中间差异过大,整块显示)")); } } outList.AddRange(mid); for (int i = 0; i < suf; i++) outList.Add(new DiffLine(0, a[n - suf + i])); return outList; } private static List LcsCore(List a, int ao, int na, List b, int bo, int nb, bool ignoreSpace, bool ignoreCase) { // Hirschberg 分治:时间 O(n*m),内存 O(n+m),结果与标准 LCS 一致 List res = new List(); Hirschberg(a, ao, na, b, bo, nb, ignoreSpace, ignoreCase, res); return res; } // 计算 LCS 长度表的最后一行(滚动两行) private static int[] LcsLastRow(List a, int ao, int n, List b, int bo, int m, bool ignoreSpace, bool ignoreCase) { int[] prev = new int[m + 1]; int[] cur = new int[m + 1]; for (int i = 1; i <= n; i++) { string sa = Norm(a[ao + i - 1], ignoreSpace, ignoreCase); cur[0] = 0; for (int j = 1; j <= m; j++) { if (sa == Norm(b[bo + j - 1], ignoreSpace, ignoreCase)) cur[j] = prev[j - 1] + 1; else cur[j] = prev[j] >= cur[j - 1] ? prev[j] : cur[j - 1]; } int[] t = prev; prev = cur; cur = t; } return prev; } private static void Hirschberg(List a, int ao, int n, List b, int bo, int m, bool ignoreSpace, bool ignoreCase, List res) { if (n == 0) { for (int j = 0; j < m; j++) res.Add(new DiffLine(2, b[bo + j])); return; } if (m == 0) { for (int i = 0; i < n; i++) res.Add(new DiffLine(1, a[ao + i])); return; } if (n == 1) { string sa = Norm(a[ao], ignoreSpace, ignoreCase); int hit = -1; for (int j = 0; j < m; j++) if (sa == Norm(b[bo + j], ignoreSpace, ignoreCase)) { hit = j; break; } if (hit < 0) { res.Add(new DiffLine(1, a[ao])); for (int j = 0; j < m; j++) res.Add(new DiffLine(2, b[bo + j])); } else { for (int j = 0; j < hit; j++) res.Add(new DiffLine(2, b[bo + j])); res.Add(new DiffLine(0, a[ao])); for (int j = hit + 1; j < m; j++) res.Add(new DiffLine(2, b[bo + j])); } return; } int mid = n / 2; int[] l1 = LcsLastRow(a, ao, mid, b, bo, m, ignoreSpace, ignoreCase); // 反转后半段再算,得到 l2[j] = 后半段与 b[j..m) 的 LCS int n2 = n - mid; List aRev = new List(n2); for (int i = 0; i < n2; i++) aRev.Add(a[ao + n - 1 - i]); List bRev = new List(m); for (int j = 0; j < m; j++) bRev.Add(b[bo + m - 1 - j]); int[] l2 = LcsLastRow(aRev, 0, n2, bRev, 0, m, ignoreSpace, ignoreCase); int best = -1, bestJ = 0; for (int j = 0; j <= m; j++) { int v = l1[j] + l2[m - j]; if (v > best) { best = v; bestJ = j; } } Hirschberg(a, ao, mid, b, bo, bestJ, ignoreSpace, ignoreCase, res); Hirschberg(a, ao + mid, n2, b, bo + bestJ, m - bestJ, ignoreSpace, ignoreCase, res); } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length >= 3 && args[0] == "--selftest") { Environment.Exit(RunSelfTest(args[1], args[2])); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TextDiffForm()); } // 命令行自测:对比两个文件,输出统计。0=过 1=失败 public static int RunSelfTest(string fileA, string fileB) { StringBuilder log = new StringBuilder(); try { List a = new List(File.ReadAllLines(fileA, Encoding.UTF8)); List b = new List(File.ReadAllLines(fileB, Encoding.UTF8)); List diff = TextDiffForm.Diff(a, b, false, false); int same = 0, del = 0, add = 0; foreach (TextDiffForm.DiffLine dl in diff) { if (dl.Kind == 0) same++; else if (dl.Kind == 1) del++; else add++; } // 自洽校验:删+同 = 左行数;加+同 = 右行数;回放顺序得到的是原文件的行序列 bool ok = (del + same) == a.Count && (add + same) == b.Count; // 顺序校验:取出左独有+相同的文本应重组出左文件 List la = new List(), ra = new List(); foreach (TextDiffForm.DiffLine dl in diff) { if (dl.Kind != 2) la.Add(dl.Text); if (dl.Kind != 1) ra.Add(dl.Text); } for (int i = 0; i < Math.Min(la.Count, a.Count) && ok; i++) if (la[i] != a[i]) ok = false; for (int i = 0; i < Math.Min(ra.Count, b.Count) && ok; i++) if (ra[i] != b[i]) ok = false; log.AppendLine("左 " + a.Count + " 行,右 " + b.Count + " 行 → 相同 " + same + " 删 " + del + " 增 " + add + (ok ? " PASS" : " FAIL")); File.AppendAllText("selftest-textdiff.txt", log.ToString(), Encoding.UTF8); Console.WriteLine(log.ToString()); return ok ? 0 : 1; } catch (Exception ex) { log.AppendLine("异常: " + ex.GetType().Name + " " + ex.Message); File.AppendAllText("selftest-textdiff.txt", log.ToString(), Encoding.UTF8); Console.WriteLine(log.ToString()); return 1; } } } }