// 文件时间戳批量修改 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:把文件夹里文件的时间统一改成某个时间、整体平移若干天、或对齐到参考文件 // 边界:这是少数「就地改」的工具——每次应用前自动写一份时间备份 CSV,可用它还原 // 原理:File.SetCreationTime / SetLastWriteTime / SetLastAccessTime,逐项可选 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class TouchOps { public const int ModeFixed = 0; // 统一设为某个时间 public const int ModeShift = 1; // 在原时间上平移 public const int ModeRef = 2; // 对齐到参考文件 public class Options { public int Mode = ModeFixed; public DateTime Fixed = DateTime.Now; public double ShiftDays; public double ShiftHours; public double ShiftMinutes; public string RefFile = ""; public bool Recursive = true; public bool SetCreated = false; public bool SetModified = true; public bool SetAccessed = false; } public class Row { public string File; public string OldModified; public string NewModified; public string Note; public bool Changed; } public class Result { public List Rows = new List(); public int Changed; public int Failed; public int Skipped; public string BackupFile = ""; } public static DateTime ParseTime(string s) { if (s == null) throw new ArgumentException("时间是空的"); string t = s.Trim(); string[] patterns = new string[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/M/d HH:mm:ss", "yyyy/M/d HH:mm", "yyyy/M/d", "yyyyMMddHHmmss", "yyyyMMdd" }; DateTime d; if (DateTime.TryParseExact(t, patterns, CultureInfo.InvariantCulture, DateTimeStyles.None, out d)) return d; if (DateTime.TryParse(t, out d)) return d; throw new ArgumentException("时间格式看不懂:" + s + "(例:2026-01-01 12:30)"); } /* 目标时间:固定 / 平移 / 参考文件 */ public static DateTime TargetTime(DateTime old, Options o, DateTime refTime) { if (o.Mode == ModeShift) return old.AddDays(o.ShiftDays).AddHours(o.ShiftHours).AddMinutes(o.ShiftMinutes); if (o.Mode == ModeRef) return refTime; return o.Fixed; } public static Options RefOptions(string refFile, Options baseOpt) { Options o = baseOpt; o.RefFile = refFile; o.Mode = ModeRef; return o; } static string Fmt(DateTime d) { return d == DateTime.MinValue ? "" : d.ToString("yyyy-MM-dd HH:mm:ss"); } public static Result Apply(string folder, Options o, bool dryRun) { if (!Directory.Exists(folder)) throw new IOException("目录不存在:" + folder); DateTime refCreated = DateTime.MinValue, refModified = DateTime.MinValue, refAccessed = DateTime.MinValue; if (o.Mode == ModeRef) { if (string.IsNullOrEmpty(o.RefFile) || !File.Exists(o.RefFile)) throw new IOException("参考文件不存在:" + o.RefFile); refCreated = File.GetCreationTime(o.RefFile); refModified = File.GetLastWriteTime(o.RefFile); refAccessed = File.GetLastAccessTime(o.RefFile); } Result r = new Result(); string[] files = Directory.GetFiles(folder, "*.*", o.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); List backup = new List(); if (!dryRun) { r.BackupFile = Path.Combine(folder, "时间戳备份-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".csv"); backup.Add("路径,原创建时间,原修改时间,原访问时间"); } foreach (string f in files) { Row row = new Row(); row.File = RelName(folder, f); try { DateTime oldC = File.GetCreationTime(f); DateTime oldM = File.GetLastWriteTime(f); DateTime oldA = File.GetLastAccessTime(f); row.OldModified = Fmt(oldM); DateTime newC = o.Mode == ModeRef ? refCreated : TargetTime(oldC, o, DateTime.MinValue); DateTime newM = o.Mode == ModeRef ? refModified : TargetTime(oldM, o, DateTime.MinValue); DateTime newA = o.Mode == ModeRef ? refAccessed : TargetTime(oldA, o, DateTime.MinValue); row.NewModified = Fmt(newM); if (dryRun) { row.Note = "预览(未修改)"; row.Changed = true; r.Rows.Add(row); continue; } if (!dryRun) backup.Add(CsvCell(row.File) + "," + CsvCell(Fmt(oldC)) + "," + CsvCell(Fmt(oldM)) + "," + CsvCell(Fmt(oldA))); // 顺序:先写访问时间,最后写修改时间——某些同步盘会在写入后回填时间 if (o.SetAccessed) File.SetLastAccessTime(f, newA); if (o.SetCreated) File.SetCreationTime(f, newC); if (o.SetModified) File.SetLastWriteTime(f, newM); row.Changed = true; row.Note = "已修改"; r.Changed++; r.Rows.Add(row); } catch (Exception ex) { row.Note = "失败:" + ex.Message; r.Failed++; r.Rows.Add(row); } } if (!dryRun && backup.Count > 1) { File.WriteAllLines(r.BackupFile, backup.ToArray(), new UTF8Encoding(true)); } else if (!dryRun) { r.BackupFile = ""; // 没有文件就没有备份 } return r; } /* 从备份 CSV 还原:路径是相对扫描根的,baseFolder 传回同一个根 */ public static Result Restore(string baseFolder, string backupFile) { if (!File.Exists(backupFile)) throw new IOException("备份文件不存在:" + backupFile); Result r = new Result(); string[] lines = File.ReadAllLines(backupFile, new UTF8Encoding(true)); for (int i = 1; i < lines.Length; i++) { if (lines[i].Trim().Length == 0) continue; string[] cells = SplitCsv(lines[i]); Row row = new Row(); row.File = cells.Length > 0 ? cells[0] : ""; try { if (cells.Length < 4) throw new IOException("列数不对"); string full = Path.IsPathRooted(row.File) ? row.File : Path.Combine(baseFolder, row.File); if (!File.Exists(full)) { row.Note = "文件不在了,跳过"; r.Skipped++; r.Rows.Add(row); continue; } DateTime c = ParseTime(cells[1]); DateTime m = ParseTime(cells[2]); DateTime a = ParseTime(cells[3]); File.SetLastAccessTime(full, a); File.SetCreationTime(full, c); File.SetLastWriteTime(full, m); row.OldModified = ""; row.NewModified = Fmt(m); row.Changed = true; row.Note = "已还原"; r.Changed++; r.Rows.Add(row); } catch (Exception ex) { row.Note = "失败:" + ex.Message; r.Failed++; r.Rows.Add(row); } } return r; } public static string CsvCell(string s) { if (s == null) return ""; if (s.IndexOf(',') >= 0 || s.IndexOf('"') >= 0) return "\"" + s.Replace("\"", "\"\"") + "\""; return s; } /* 小型 CSV 解析:只处理双引号包裹与 "" 转义,够本工具自己写的备份用 */ public static string[] SplitCsv(string line) { List cells = new List(); StringBuilder cur = new StringBuilder(); bool inQuote = false; for (int i = 0; i < line.Length; i++) { char ch = line[i]; if (inQuote) { if (ch == '"') { if (i + 1 < line.Length && line[i + 1] == '"') { cur.Append('"'); i++; } else inQuote = false; } else cur.Append(ch); } else { if (ch == '"') inQuote = true; else if (ch == ',') { cells.Add(cur.ToString()); cur.Length = 0; } else cur.Append(ch); } } cells.Add(cur.ToString()); return cells.ToArray(); } public static string RelName(string root, string file) { return file.Substring(root.TrimEnd('\\').Length).TrimStart('\\'); } public static string ShiftText(Options o) { StringBuilder sb = new StringBuilder(); if (o.ShiftDays != 0) sb.Append(o.ShiftDays.ToString("+0.##;-0.##") + " 天 "); if (o.ShiftHours != 0) sb.Append(o.ShiftHours.ToString("+0.##;-0.##") + " 小时 "); if (o.ShiftMinutes != 0) sb.Append(o.ShiftMinutes.ToString("+0.##;-0.##") + " 分 "); return sb.Length == 0 ? "0(没填偏移量)" : sb.ToString().Trim(); } } public class TouchBatchForm : Form { private TextBox txtDir; private Button btnPick; private ComboBox cbMode; private TextBox txtFixed; private TextBox txtDays, txtHours, txtMinutes; private TextBox txtRef; private Button btnRef; private CheckBox chkCreated, chkModified, chkAccessed, chkRecursive; private Button btnPreview, btnApply, btnRestore; private ListView lv; private Label lblStatus; private int _previewCount; public TouchBatchForm() { 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(860, 580); this.MinimumSize = new Size(760, 520); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "统一修改文件的创建/修改/访问时间:可整体平移,也可对齐到某个参考文件"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 30; txtDir = new TextBox(); txtDir.Location = new Point(x, y); txtDir.Size = new Size(660, 26); this.Controls.Add(txtDir); btnPick = new Button(); btnPick.Text = "浏览…"; btnPick.Location = new Point(692, y - 1); btnPick.Size = new Size(90, 28); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 40; Label lbMode = new Label(); lbMode.Text = "方式"; lbMode.Location = new Point(x, y + 3); lbMode.AutoSize = true; this.Controls.Add(lbMode); cbMode = new ComboBox(); cbMode.DropDownStyle = ComboBoxStyle.DropDownList; cbMode.Location = new Point(x + 46, y); cbMode.Size = new Size(220, 26); cbMode.Items.Add("统一设为指定时间"); cbMode.Items.Add("在原时间上整体平移"); cbMode.Items.Add("对齐到参考文件的时间"); cbMode.SelectedIndex = 0; cbMode.SelectedIndexChanged += new EventHandler(ModeChanged); this.Controls.Add(cbMode); y += 38; Label lbFix = new Label(); lbFix.Text = "指定时间"; lbFix.Location = new Point(x, y + 3); lbFix.AutoSize = true; this.Controls.Add(lbFix); txtFixed = new TextBox(); txtFixed.Location = new Point(x + 72, y); txtFixed.Size = new Size(180, 26); txtFixed.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); this.Controls.Add(txtFixed); Label lbShift = new Label(); lbShift.Text = "平移"; lbShift.Location = new Point(x + 272, y + 3); lbShift.AutoSize = true; this.Controls.Add(lbShift); txtDays = new TextBox(); txtDays.Location = new Point(x + 312, y); txtDays.Size = new Size(56, 26); txtDays.Text = "0"; this.Controls.Add(txtDays); Label lbD = new Label(); lbD.Text = "天"; lbD.Location = new Point(x + 372, y + 3); lbD.AutoSize = true; this.Controls.Add(lbD); txtHours = new TextBox(); txtHours.Location = new Point(x + 394, y); txtHours.Size = new Size(50, 26); txtHours.Text = "0"; this.Controls.Add(txtHours); Label lbH = new Label(); lbH.Text = "小时"; lbH.Location = new Point(x + 448, y + 3); lbH.AutoSize = true; this.Controls.Add(lbH); txtMinutes = new TextBox(); txtMinutes.Location = new Point(x + 490, y); txtMinutes.Size = new Size(50, 26); txtMinutes.Text = "0"; this.Controls.Add(txtMinutes); Label lbM = new Label(); lbM.Text = "分(负数表示往前)"; lbM.Location = new Point(x + 544, y + 3); lbM.AutoSize = true; lbM.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lbM); y += 38; Label lbRef = new Label(); lbRef.Text = "参考文件"; lbRef.Location = new Point(x, y + 3); lbRef.AutoSize = true; this.Controls.Add(lbRef); txtRef = new TextBox(); txtRef.Location = new Point(x + 72, y); txtRef.Size = new Size(430, 26); this.Controls.Add(txtRef); btnRef = new Button(); btnRef.Text = "选…"; btnRef.Location = new Point(x + 508, y - 1); btnRef.Size = new Size(50, 28); btnRef.Click += new EventHandler(RefClick); this.Controls.Add(btnRef); y += 40; chkCreated = new CheckBox(); chkCreated.Text = "创建时间"; chkCreated.Location = new Point(x, y); chkCreated.AutoSize = true; this.Controls.Add(chkCreated); chkModified = new CheckBox(); chkModified.Text = "修改时间"; chkModified.Location = new Point(x + 110, y); chkModified.AutoSize = true; chkModified.Checked = true; this.Controls.Add(chkModified); chkAccessed = new CheckBox(); chkAccessed.Text = "访问时间"; chkAccessed.Location = new Point(x + 220, y); chkAccessed.AutoSize = true; this.Controls.Add(chkAccessed); chkRecursive = new CheckBox(); chkRecursive.Text = "含子文件夹"; chkRecursive.Location = new Point(x + 330, y); chkRecursive.AutoSize = true; chkRecursive.Checked = true; this.Controls.Add(chkRecursive); y += 38; btnPreview = new Button(); btnPreview.Text = "预览"; btnPreview.Location = new Point(x, y); btnPreview.Size = new Size(100, 34); btnPreview.Click += new EventHandler(PreviewClick); this.Controls.Add(btnPreview); btnApply = new Button(); btnApply.Text = "应用修改"; btnApply.Location = new Point(x + 112, y); btnApply.Size = new Size(130, 34); btnApply.BackColor = Color.FromArgb(0, 145, 88); btnApply.ForeColor = Color.White; btnApply.FlatStyle = FlatStyle.Flat; btnApply.Click += new EventHandler(ApplyClick); this.Controls.Add(btnApply); btnRestore = new Button(); btnRestore.Text = "从备份还原…"; btnRestore.Location = new Point(x + 254, y); btnRestore.Size = new Size(130, 34); btnRestore.Click += new EventHandler(RestoreClick); this.Controls.Add(btnRestore); y += 46; lblStatus = new Label(); lblStatus.Text = "默认只改「修改时间」。先点「预览」看新旧对照,再点应用;应用时自动写时间备份 CSV。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); y += 26; lv = new ListView(); lv.View = View.Details; lv.FullRowSelect = true; lv.Location = new Point(x, y); lv.Size = new Size(820, 330); lv.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lv.Columns.Add("文件", 380); lv.Columns.Add("原修改时间", 160); lv.Columns.Add("新修改时间", 160); lv.Columns.Add("备注", 120); this.Controls.Add(lv); ModeChanged(null, null); } private void ModeChanged(object sender, EventArgs e) { bool fixedMode = cbMode.SelectedIndex == TouchOps.ModeFixed; bool shiftMode = cbMode.SelectedIndex == TouchOps.ModeShift; bool refMode = cbMode.SelectedIndex == TouchOps.ModeRef; txtFixed.Enabled = fixedMode; txtDays.Enabled = shiftMode; txtHours.Enabled = shiftMode; txtMinutes.Enabled = shiftMode; txtRef.Enabled = refMode; btnRef.Enabled = refMode; } private void PickClick(object sender, EventArgs e) { FolderBrowserDialog dlg = new FolderBrowserDialog(); if (Directory.Exists(txtDir.Text)) dlg.SelectedPath = txtDir.Text; if (dlg.ShowDialog(this) == DialogResult.OK) txtDir.Text = dlg.SelectedPath; } private void RefClick(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog(this) == DialogResult.OK) txtRef.Text = dlg.FileName; } private void FormDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void FormDragDrop(object sender, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); if (paths.Length == 0) return; if (Directory.Exists(paths[0])) txtDir.Text = paths[0]; else if (File.Exists(paths[0])) txtRef.Text = paths[0]; } private TouchOps.Options Options() { TouchOps.Options o = new TouchOps.Options(); o.Mode = cbMode.SelectedIndex; if (o.Mode == TouchOps.ModeFixed) o.Fixed = TouchOps.ParseTime(txtFixed.Text); o.ShiftDays = ParseNum(txtDays.Text, "天数"); o.ShiftHours = ParseNum(txtHours.Text, "小时"); o.ShiftMinutes = ParseNum(txtMinutes.Text, "分钟"); o.RefFile = (txtRef.Text ?? "").Trim(); o.Recursive = chkRecursive.Checked; o.SetCreated = chkCreated.Checked; o.SetModified = chkModified.Checked; o.SetAccessed = chkAccessed.Checked; if (!o.SetCreated && !o.SetModified && !o.SetAccessed) throw new ArgumentException("三个时间都没勾,等于什么也不改。"); return o; } static double ParseNum(string s, string what) { if ((s ?? "").Trim().Length == 0) return 0; double d; if (!double.TryParse(s.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out d)) throw new ArgumentException(what + "不是数字:" + s); return d; } private string Dir() { return (txtDir.Text ?? "").Trim(); } private void PreviewClick(object sender, EventArgs e) { string dir = Dir(); if (dir.Length == 0 || !Directory.Exists(dir)) { Warn("先选一个存在的文件夹。"); return; } try { TouchOps.Options o = Options(); TouchOps.Result r = TouchOps.Apply(dir, o, true); Fill(r); _previewCount = r.Rows.Count; lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "预览 " + r.Rows.Count + " 个文件,还没有任何修改。确认后点「应用修改」。"; } catch (Exception ex) { Warn(ex.Message); } } private void ApplyClick(object sender, EventArgs e) { string dir = Dir(); if (dir.Length == 0 || !Directory.Exists(dir)) { Warn("先选一个存在的文件夹。"); return; } try { TouchOps.Options o = Options(); TouchOps.Result pre = TouchOps.Apply(dir, o, true); string what = o.SetModified ? "修改时间" : ""; if (o.SetCreated) what += (what.Length > 0 ? "、" : "") + "创建时间"; if (o.SetAccessed) what += (what.Length > 0 ? "、" : "") + "访问时间"; string head = "将修改 " + pre.Rows.Count + " 个文件的" + what + "。\r\n"; if (o.Mode == TouchOps.ModeFixed) head += "目标时间:" + o.Fixed.ToString("yyyy-MM-dd HH:mm:ss"); else if (o.Mode == TouchOps.ModeShift) head += "平移量:" + TouchOps.ShiftText(o); else head += "参考文件:" + o.RefFile; if (MessageBox.Show(head + "\r\n\r\n修改前会自动在同目录写一份「时间戳备份-*.csv」,可用它还原。继续?", "确认修改", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) return; TouchOps.Result r = TouchOps.Apply(dir, o, false); Fill(r); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "改了 " + r.Changed + " 个文件,失败 " + r.Failed + "。" + (r.BackupFile.Length > 0 ? "备份:" + Path.GetFileName(r.BackupFile) : ""); } catch (Exception ex) { Warn(ex.Message); } } private void RestoreClick(object sender, EventArgs e) { string dir = Dir(); if (dir.Length == 0 || !Directory.Exists(dir)) { Warn("先把要还原的文件夹选上(备份里的路径是相对这个文件夹的)。"); return; } OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "时间戳备份|时间戳备份-*.csv|CSV|*.csv"; dlg.InitialDirectory = dir; if (dlg.ShowDialog(this) != DialogResult.OK) return; if (MessageBox.Show("按备份把时间改回去?以备份里记录的时间为准。", "确认还原", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return; try { TouchOps.Result r = TouchOps.Restore(dir, dlg.FileName); Fill(r); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "还原 " + r.Changed + " 个,跳过 " + r.Skipped + " 个(文件已不在),失败 " + r.Failed + "。"; } catch (Exception ex) { Warn(ex.Message); } } private void Fill(TouchOps.Result r) { lv.BeginUpdate(); lv.Items.Clear(); foreach (TouchOps.Row row in r.Rows) { ListViewItem li = new ListViewItem(row.File); li.SubItems.Add(row.OldModified); li.SubItems.Add(row.NewModified); li.SubItems.Add(row.Note); if (row.Note.StartsWith("失败")) li.ForeColor = Color.FromArgb(190, 90, 40); lv.Items.Add(li); } lv.EndUpdate(); } private void Warn(string msg) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = msg; } } // ───────────────────────── 自测 ───────────────────────── public static class TouchSelfTest { 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("文件时间戳批量修改 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-touch-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); string a = Path.Combine(baseDir, "a.txt"); string b = Path.Combine(baseDir, "b.txt"); string c = Path.Combine(baseDir, "c.log"); string sub = Path.Combine(baseDir, "sub"); Directory.CreateDirectory(sub); string d = Path.Combine(sub, "d.txt"); File.WriteAllText(a, "aaa", new UTF8Encoding(false)); File.WriteAllText(b, "bbb", new UTF8Encoding(false)); File.WriteAllText(c, "ccc", new UTF8Encoding(false)); File.WriteAllText(d, "ddd", new UTF8Encoding(false)); DateTime t0 = new DateTime(2021, 5, 6, 7, 8, 9); File.SetLastWriteTime(a, t0); File.SetLastWriteTime(b, t0.AddDays(10)); File.SetLastWriteTime(c, t0.AddDays(20)); File.SetLastWriteTime(d, t0); File.SetCreationTime(a, t0.AddDays(-1)); File.SetCreationTime(b, t0.AddDays(-1)); File.SetCreationTime(c, t0.AddDays(-1)); File.SetCreationTime(d, t0.AddDays(-1)); Check("时间解析(日期+时间)", TouchOps.ParseTime("2026-01-02 03:04").ToString("yyyy-MM-dd HH:mm"), "2026-01-02 03:04"); Check("时间解析(只有日期)", TouchOps.ParseTime("2026-01-02").ToString("yyyy-MM-dd"), "2026-01-02"); Check("时间解析(斜杠)", TouchOps.ParseTime("2026/1/2 3:04:05").ToString("yyyy-MM-dd HH:mm:ss"), "2026-01-02 03:04:05"); bool threw = false; try { TouchOps.ParseTime("不是时间"); } catch { threw = true; } Check("非法时间抛异常", threw ? "threw" : "silent", "threw"); // 固定时间:只改修改时间 TouchOps.Options o = new TouchOps.Options(); o.Mode = TouchOps.ModeFixed; o.Fixed = new DateTime(2020, 1, 2, 3, 4, 5); o.SetModified = true; o.SetCreated = false; TouchOps.Result pre = TouchOps.Apply(baseDir, o, true); Check("预览是 4 个文件", pre.Rows.Count, 4); Check("预览不改文件", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-06 07:08:09"); Check("预览不写备份", pre.BackupFile, ""); TouchOps.Result r1 = TouchOps.Apply(baseDir, o, false); Check("改了 4 个", r1.Changed, 4); Check("a 修改时间已变", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2020-01-02 03:04:05"); Check("d 也在子目录里被改", File.GetLastWriteTime(d).ToString("yyyy-MM-dd HH:mm:ss"), "2020-01-02 03:04:05"); Check("创建时间没动(未勾选)", File.GetCreationTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-05 07:08:09"); Check("备份文件已生成", File.Exists(r1.BackupFile), true); string[] bk = File.ReadAllLines(r1.BackupFile, new UTF8Encoding(true)); Check("备份有表头+4 行", bk.Length, 5); bool founded = false; foreach (string line in bk) if (line.IndexOf("2021-05-06 07:08:09") >= 0) founded = true; Check("备份记录原时间", founded, true); Check("文件内容没变", File.ReadAllText(a, new UTF8Encoding(false)), "aaa"); // 还原 TouchOps.Result r2 = TouchOps.Restore(baseDir, r1.BackupFile); Check("还原 4 个", r2.Changed, 4); Check("a 时间已还原", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-06 07:08:09"); Check("b 时间已还原", File.GetLastWriteTime(b).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-16 07:08:09"); Check("创建时间也还原", File.GetCreationTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-05 07:08:09"); // 平移 +2 天 3 小时 TouchOps.Options o2 = new TouchOps.Options(); o2.Mode = TouchOps.ModeShift; o2.ShiftDays = 2; o2.ShiftHours = 3; o2.SetModified = true; TouchOps.Apply(baseDir, o2, false); Check("平移后 a", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-08 10:08:09"); Check("平移后 c", File.GetLastWriteTime(c).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-28 10:08:09"); // 负数平移 TouchOps.Options o3 = new TouchOps.Options(); o3.Mode = TouchOps.ModeShift; o3.ShiftDays = -2; o3.ShiftHours = -3; o3.SetModified = true; TouchOps.Apply(baseDir, o3, false); Check("负向平移回原点", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2021-05-06 07:08:09"); // 对齐参考文件 string refFile = Path.Combine(baseDir, "ref.txt"); File.WriteAllText(refFile, "ref", new UTF8Encoding(false)); DateTime rt = new DateTime(2019, 9, 9, 9, 9, 9); File.SetLastWriteTime(refFile, rt); TouchOps.Options o4 = new TouchOps.Options(); o4.Mode = TouchOps.ModeRef; o4.RefFile = refFile; o4.SetModified = true; TouchOps.Apply(baseDir, o4, false); Check("对齐参考文件 a", File.GetLastWriteTime(a).ToString("yyyy-MM-dd HH:mm:ss"), "2019-09-09 09:09:09"); Check("对齐参考文件 d", File.GetLastWriteTime(d).ToString("yyyy-MM-dd HH:mm:ss"), "2019-09-09 09:09:09"); // 不递归 TouchOps.Options o5 = new TouchOps.Options(); o5.Mode = TouchOps.ModeFixed; o5.Fixed = new DateTime(2018, 1, 1, 0, 0, 0); o5.Recursive = false; o5.SetModified = true; TouchOps.Result r5 = TouchOps.Apply(baseDir, o5, false); int dCount = 0; foreach (TouchOps.Row row in r5.Rows) if (row.File == "sub\\d.txt") dCount++; Check("不递归时不碰子目录", dCount, 0); Check("不递归时子目录文件时间没变", File.GetLastWriteTime(d).ToString("yyyy-MM-dd"), "2019-09-09"); // 参考文件不存在 TouchOps.Options bad = new TouchOps.Options(); bad.Mode = TouchOps.ModeRef; bad.RefFile = Path.Combine(baseDir, "none.txt"); threw = false; try { TouchOps.Apply(baseDir, bad, false); } catch { threw = true; } Check("参考文件不存在抛异常", threw ? "threw" : "silent", "threw"); // CSV 解析带引号 string[] cells = TouchOps.SplitCsv("\"a,b\\c.txt\",\"2020-01-01 00:00:00\",x,y"); Check("CSV 引号解析数", cells.Length, 4); Check("CSV 引号内容", cells[0], "a,b\\c.txt"); Check("CSV 转义双引号", TouchOps.SplitCsv("\"he said \"\"hi\"\"\"")[0], "he said \"hi\""); threw = false; try { TouchOps.Apply(Path.Combine(baseDir, "nope"), o, false); } catch { threw = true; } Check("目录不存在抛异常", threw ? "threw" : "silent", "threw"); } 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-touchbatch.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(TouchSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TouchBatchForm()); } } }