From 74c34c0cbbc2a6c008fd1fc69ad23f5008a26dd6 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sun, 6 Dec 2026 14:10:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=B9=E7=9B=AE=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 +- DailyFileSync.csproj | 12 ++ DailyFileSync.slnx | 3 + MainForm.cs | 344 ++++++++++++++++++++++++++++++++++++++++ OfflineSetup.iss | 47 ++++++ Program.cs | 36 +++++ README.md | 38 +++++ StartupRegistration.cs | 43 +++++ SyncEngine.cs | 226 ++++++++++++++++++++++++++ SyncSettings.cs | 66 ++++++++ app.manifest | 21 +++ build-offline-setup.ps1 | 44 +++++ build-standalone.ps1 | 37 +++++ build.ps1 | 24 +++ 14 files changed, 944 insertions(+), 1 deletion(-) create mode 100644 DailyFileSync.csproj create mode 100644 DailyFileSync.slnx create mode 100644 MainForm.cs create mode 100644 OfflineSetup.iss create mode 100644 Program.cs create mode 100644 README.md create mode 100644 StartupRegistration.cs create mode 100644 SyncEngine.cs create mode 100644 SyncSettings.cs create mode 100644 app.manifest create mode 100644 build-offline-setup.ps1 create mode 100644 build-standalone.ps1 create mode 100644 build.ps1 diff --git a/.gitignore b/.gitignore index 9491a2f..c9b9f92 100644 --- a/.gitignore +++ b/.gitignore @@ -360,4 +360,6 @@ MigrationBackup/ .ionide/ # Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file +FodyWeavers.xsd + +/dist/ diff --git a/DailyFileSync.csproj b/DailyFileSync.csproj new file mode 100644 index 0000000..04f75e0 --- /dev/null +++ b/DailyFileSync.csproj @@ -0,0 +1,12 @@ + + + WinExe + net10.0-windows + true + app.manifest + false + + + + + diff --git a/DailyFileSync.slnx b/DailyFileSync.slnx new file mode 100644 index 0000000..6755c20 --- /dev/null +++ b/DailyFileSync.slnx @@ -0,0 +1,3 @@ + + + diff --git a/MainForm.cs b/MainForm.cs new file mode 100644 index 0000000..c54c55e --- /dev/null +++ b/MainForm.cs @@ -0,0 +1,344 @@ +using System; +using System.Drawing; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +internal sealed class MainForm : Form +{ + private const string AppName = "每日文件同步"; + private readonly TextBox source = new TextBox { AccessibleName = "源目录" }; + private readonly TextBox destination = new TextBox { AccessibleName = "目标目录" }; + private readonly DateTimePicker time = new DateTimePicker + { + AccessibleName = "每日同步时间", Format = DateTimePickerFormat.Custom, + CustomFormat = "HH:mm", ShowUpDown = true, Width = 95 + }; + private readonly CheckBox launchAtLogin = new CheckBox + { + Text = "开机自动启动", AutoSize = true, Anchor = AnchorStyles.Left + }; + private readonly Label nextRun = new Label { AutoSize = true, Margin = new Padding(3, 10, 3, 10) }; + private readonly TextBox status = new TextBox + { + AccessibleName = "同步状态", Multiline = true, ReadOnly = true, Dock = DockStyle.Fill, + ScrollBars = ScrollBars.Vertical + }; + private readonly Button selectSource = new Button { Text = "浏览…", AutoSize = true }; + private readonly Button selectDestination = new Button { Text = "浏览…", AutoSize = true }; + private readonly Button save = new Button { Text = "保存设置", AutoSize = true }; + private readonly Button sync = new Button { Text = "立即同步", AutoSize = true }; + private readonly ContextMenuStrip trayMenu = new ContextMenuStrip(); + private readonly NotifyIcon tray; + private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 1000 }; + private SyncSettings settings; + private CancellationTokenSource activeSync; + private bool exiting; + private bool allowClose; + private bool trayHintShown; + + public MainForm() + { + Text = AppName; + Icon = SystemIcons.Application; + StartPosition = FormStartPosition.CenterScreen; + AutoScaleMode = AutoScaleMode.Dpi; + ClientSize = new Size(610, 370); + MinimumSize = new Size(490, 365); + BuildLayout(); + + selectSource.Click += (sender, args) => Browse(source, "选择源目录"); + selectDestination.Click += (sender, args) => Browse(destination, "选择目标目录"); + save.Click += (sender, args) => + { + if (SaveSettings()) + { + status.Text = "设置已保存。"; + CheckSchedule(); + } + }; + sync.Click += (sender, args) => + { + if (SaveSettings()) StartSync(null); + }; + + ToolStripItem open = trayMenu.Items.Add("打开窗口", null, (sender, args) => OpenWindow()); + open.Font = new Font(open.Font, FontStyle.Bold); + trayMenu.Items.Add(new ToolStripSeparator()); + trayMenu.Items.Add("退出程序", null, (sender, args) => ExitProgram()); + tray = new NotifyIcon { Text = AppName, Icon = Icon, ContextMenuStrip = trayMenu, Visible = true }; + tray.DoubleClick += (sender, args) => OpenWindow(); + + FormClosing += HideOrClose; + timer.Tick += (sender, args) => CheckSchedule(); + LoadSettings(); + try { launchAtLogin.Checked = StartupRegistration.IsEnabled(); } + catch (Exception error) + { + status.AppendText("\r\n无法读取开机自动启动设置。\r\n" + error.Message); + } + launchAtLogin.Click += (sender, args) => ChangeStartupSetting(); + } + + public void Start(bool startInTray) + { + if (startInTray) + CreateHandle(); // Keep the form hidden while allowing Close to raise FormClosed. + else + Show(); + timer.Start(); + } + + private void ChangeStartupSetting() + { + bool enabled = launchAtLogin.Checked; + try { StartupRegistration.SetEnabled(enabled); } + catch (Exception error) + { + launchAtLogin.Checked = !enabled; + MessageBox.Show(this, error.Message, "无法更新开机自动启动设置", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + private void BuildLayout() + { + TableLayoutPanel panel = new TableLayoutPanel + { + Dock = DockStyle.Fill, Padding = new Padding(14), ColumnCount = 3, RowCount = 7 + }; + panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + for (int row = 0; row < 6; row++) + panel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + panel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + + AddField(panel, 0, "源目录", source, selectSource); + AddField(panel, 1, "目标目录", destination, selectDestination); + panel.Controls.Add(FieldLabel("每日同步时间"), 0, 2); + time.Anchor = AnchorStyles.Left; + panel.Controls.Add(time, 1, 2); + panel.Controls.Add(launchAtLogin, 0, 3); + panel.SetColumnSpan(launchAtLogin, 3); + + FlowLayoutPanel actions = new FlowLayoutPanel + { + AutoSize = true, Dock = DockStyle.Fill, WrapContents = false, + FlowDirection = FlowDirection.RightToLeft, Margin = new Padding(0, 8, 0, 0) + }; + actions.Controls.Add(sync); + actions.Controls.Add(save); + panel.Controls.Add(actions, 0, 4); + panel.SetColumnSpan(actions, 3); + panel.Controls.Add(nextRun, 0, 5); + panel.SetColumnSpan(nextRun, 3); + panel.Controls.Add(status, 0, 6); + panel.SetColumnSpan(status, 3); + Controls.Add(panel); + } + + private static Label FieldLabel(string label) + { + return new Label { Text = label, AutoSize = true, Anchor = AnchorStyles.Left }; + } + + private static void AddField(TableLayoutPanel panel, int row, string label, TextBox input, Button browse) + { + panel.Controls.Add(FieldLabel(label), 0, row); + input.Anchor = AnchorStyles.Left | AnchorStyles.Right; + panel.Controls.Add(input, 1, row); + panel.Controls.Add(browse, 2, row); + } + + private void Browse(TextBox input, string description) + { + using (FolderBrowserDialog dialog = new FolderBrowserDialog()) + { + dialog.Description = description; + if (Directory.Exists(input.Text)) dialog.SelectedPath = input.Text; + if (dialog.ShowDialog(this) == DialogResult.OK) input.Text = dialog.SelectedPath; + } + } + + private void LoadSettings() + { + try + { + settings = SyncSettings.Load(); + status.Text = settings.IsConfigured ? "等待同步。" : "选择源目录和目标目录,设置每日同步时间后保存。"; + } + catch (Exception error) + { + settings = new SyncSettings(); + status.Text = "无法读取设置。请重新填写并保存。" + Environment.NewLine + error.Message; + } + + source.Text = settings.Source; + destination.Text = settings.Destination; + time.Value = DateTime.Today.AddMinutes(settings.ScheduledMinute); + UpdateNextRun(DateTime.Now); + } + + private bool SaveSettings() + { + try + { + string sourcePath = source.Text; + string targetPath = destination.Text; + SyncEngine.ValidatePaths(ref sourcePath, ref targetPath); + bool sameFolders = String.Equals(settings.Source, sourcePath, StringComparison.OrdinalIgnoreCase) && + String.Equals(settings.Destination, targetPath, StringComparison.OrdinalIgnoreCase); + SyncSettings updated = new SyncSettings + { + Source = sourcePath, Destination = targetPath, + ScheduledMinute = time.Value.Hour * 60 + time.Value.Minute, + LastScheduledDate = sameFolders ? settings.LastScheduledDate : DateTime.MinValue + }; + updated.Save(); + settings = updated; + source.Text = sourcePath; + destination.Text = targetPath; + UpdateNextRun(DateTime.Now); + return true; + } + catch (Exception error) + { + MessageBox.Show(this, error.Message, "无法保存设置", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return false; + } + } + + private void UpdateNextRun(DateTime now) + { + if (!settings.IsConfigured) + { + nextRun.Text = "尚未设置每日同步"; + return; + } + + DateTime day = settings.LastScheduledDate.Date >= now.Date + ? settings.LastScheduledDate.Date.AddDays(1) : now.Date; + DateTime scheduled = day.AddMinutes(settings.ScheduledMinute); + nextRun.Text = scheduled <= now ? "下次定时同步:等待开始" : "下次定时同步:" + scheduled.ToString("yyyy-MM-dd HH:mm"); + } + + private void CheckSchedule() + { + if (activeSync != null || exiting) return; + DateTime now = DateTime.Now; + if (settings.IsDue(now)) StartSync(now.Date); + else UpdateNextRun(now); + } + + private async void StartSync(DateTime? scheduledDay) + { + if (activeSync != null || exiting) return; + CancellationTokenSource cancellation = new CancellationTokenSource(); + activeSync = cancellation; + SetInputsEnabled(false); + string mode = scheduledDay.HasValue ? "定时同步" : "手动同步"; + status.Text = mode + "进行中…"; + string sourcePath = settings.Source; + string targetPath = settings.Destination; + + try + { + SyncResult result = await Task.Run(() => SyncEngine.Run(sourcePath, targetPath, cancellation.Token)); + status.Text = String.Format("{0:yyyy-MM-dd HH:mm:ss} {1}{2}\r\n已复制 {3} 个文件,未变化 {4} 个,跳过链接 {5} 个,失败 {6} 项。", + DateTime.Now, mode, result.Failed == 0 ? "完成" : "完成,存在失败项", + result.Copied, result.Unchanged, result.SkippedLinks, result.Failed); + if (result.Errors.Count > 0) + status.AppendText("\r\n\r\n" + String.Join("\r\n\r\n", result.Errors)); + if (result.Failed > result.Errors.Count) + status.AppendText("\r\n\r\n另有 " + (result.Failed - result.Errors.Count) + " 项失败。"); + } + catch (OperationCanceledException) + { + status.Text = mode + "已取消。"; + scheduledDay = null; + } + catch (Exception error) + { + status.Text = mode + "失败。" + Environment.NewLine + error.Message; + } + finally + { + if (scheduledDay.HasValue) + { + settings.LastScheduledDate = scheduledDay.Value; + try { settings.Save(); } + catch (Exception error) + { + status.AppendText("\r\n无法保存本次定时同步记录。\r\n" + error.Message); + } + } + + activeSync = null; + cancellation.Dispose(); + if (exiting) FinishExit(); + else + { + SetInputsEnabled(true); + UpdateNextRun(DateTime.Now); + } + } + } + + private void SetInputsEnabled(bool enabled) + { + source.Enabled = destination.Enabled = time.Enabled = enabled; + selectSource.Enabled = selectDestination.Enabled = save.Enabled = sync.Enabled = enabled; + } + + private void HideOrClose(object sender, FormClosingEventArgs args) + { + if (allowClose || args.CloseReason == CloseReason.WindowsShutDown || args.CloseReason == CloseReason.TaskManagerClosing) + return; + + args.Cancel = true; + Hide(); + if (trayHintShown) return; + trayHintShown = true; + tray.ShowBalloonTip(2500, AppName, "程序仍在通知区域运行。右键图标可打开窗口或退出。", ToolTipIcon.Info); + } + + private void OpenWindow() + { + if (exiting) return; + Show(); + if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; + Activate(); + } + + private void ExitProgram() + { + if (exiting) return; + exiting = true; + timer.Stop(); + if (activeSync == null) FinishExit(); + else + { + status.Text = "正在取消同步并退出…"; + activeSync.Cancel(); + } + } + + private void FinishExit() + { + allowClose = true; + tray.Visible = false; + Close(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + timer.Dispose(); + tray.Dispose(); + trayMenu.Dispose(); + } + base.Dispose(disposing); + } +} diff --git a/OfflineSetup.iss b/OfflineSetup.iss new file mode 100644 index 0000000..6ee9347 --- /dev/null +++ b/OfflineSetup.iss @@ -0,0 +1,47 @@ +#ifndef PayloadPath + #error PayloadPath is required +#endif +#ifndef PackageArchitecture + #error PackageArchitecture is required +#endif + +[Setup] +AppId=DailyFileSync +AppName=每日文件同步 +AppVersion=1.0.0 +DefaultDirName={localappdata}\Programs\DailyFileSync +DefaultGroupName=每日文件同步 +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +MinVersion=10.0.14393 +ArchitecturesAllowed={#PackageArchitecture} +AppMutex=Local\DailyFileSync-6DF99A2D +CloseApplications=no +UninstallDisplayIcon={app}\DailyFileSync.exe +OutputBaseFilename={#PackageName} +Compression=lzma2/fast +SolidCompression=yes +WizardStyle=modern + +[Files] +Source: "{#PayloadPath}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{autoprograms}\每日文件同步"; Filename: "{app}\DailyFileSync.exe"; WorkingDir: "{app}" + +[Run] +Filename: "{app}\DailyFileSync.exe"; WorkingDir: "{app}"; Description: "打开每日文件同步"; Flags: nowait postinstall skipifsilent + +[Code] +procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); +var + StartupKey, StartupCommand: String; +begin + if CurUninstallStep <> usPostUninstall then + Exit; + + StartupKey := 'Software\Microsoft\Windows\CurrentVersion\Run'; + if RegQueryStringValue(HKCU, StartupKey, 'DailyFileSync', StartupCommand) and + (CompareText(StartupCommand, ExpandConstant('"{app}\DailyFileSync.exe" --background')) = 0) then + RegDeleteValue(HKCU, StartupKey, 'DailyFileSync'); +end; diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..b552c89 --- /dev/null +++ b/Program.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading; +using System.Windows.Forms; + +internal static class Program +{ + [STAThread] + private static void Main(string[] args) + { + bool startInTray = Array.Exists(args, arg => + String.Equals(arg, StartupRegistration.BackgroundArgument, StringComparison.OrdinalIgnoreCase)); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + bool firstInstance; + using (Mutex instance = new Mutex(true, "Local\\DailyFileSync-6DF99A2D", out firstInstance)) + { + if (!firstInstance) + { + if (!startInTray) + MessageBox.Show("文件同步工具已在运行,可从任务栏通知区域打开。", "每日文件同步", + MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + using (MainForm form = new MainForm()) + using (ApplicationContext loop = new ApplicationContext()) + { + form.FormClosed += (sender, eventArgs) => loop.ExitThread(); + form.Start(startInTray); + Application.Run(loop); + } + instance.ReleaseMutex(); + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..c16e562 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# 每日文件同步 + +面向 Windows 10 和 Windows 11 的桌面工具。 + +- **离线安装版** `dist/DailyFileSync-Offline-Setup-win-*.exe` 将程序和运行时一同打包。把对应架构的安装包复制到离线电脑,双击即可安装到当前用户。安装完成后,可从开始菜单打开 **每日文件同步**,也可在 Windows 设置中卸载。安装和运行都无需下载、激活或另装 .NET。适用于 Windows 10 1607 或更高版本和 Windows 11。 +- **普通版** `dist/DailyFileSync.exe` 可直接双击运行,需要系统自带的 .NET Framework 4.5 或更高版本。 +- **自包含版** `dist/DailyFileSync-standalone-win-*.zip` 附带 .NET 桌面运行时,无需安装 .NET Framework 或 .NET 桌面运行时。Intel 或 AMD 64 位系统选 `win-x64`,32 位系统选 `win-x86`,ARM 设备选 `win-arm64`。解压整个压缩包后,打开其中的 `DailyFileSync.exe`。请将同目录的运行时文件和程序一起保留。 + +不同版本共用同步设置。切换版本后,如需开机自启动,请在要使用的版本中重新勾选 **开机自动启动**。离线同步适用于本机可访问的目录,网络共享仍需处于可访问状态。托盘功能依赖 Windows 桌面组件。 + +1. 选择源目录和目标目录。目标目录可以填写尚未创建的路径,两个目录必须彼此独立。 +2. 设置每日同步的本地时间,然后点击 **保存设置**。点击 **立即同步** 也会保存当前设置并立即执行一次。 +3. 点击窗口右上角的 **×** 后,程序会继续驻留在任务栏通知区域。若图标折叠,点击通知区域的 **∧**。右键图标可 **打开窗口** 或 **退出程序**。 +4. 勾选 **开机自动启动** 后,下次登录当前 Windows 账户时,程序会直接在通知区域后台运行。勾选或取消勾选都会立即保存。如果移动了程序文件,请从新位置打开并重新勾选。 + +同步会递归复制新增或有变更的文件和空目录。文件大小或最后修改时间有差异时,程序会用源文件更新目标文件。目标目录中多余的文件会保留,源目录中的链接和重解析点会跳过。同步完成后,窗口显示复制、跳过和失败的统计。 + +如果程序在当天设定时间之后启动或从睡眠中恢复,会补跑当天尚未执行的任务。设置和上次定时执行的日期保存在 `%LOCALAPPDATA%\DailyFileSync\settings.xml`。使用托盘菜单退出后,定时同步会暂停,直到再次启动程序。 + +## 从源码构建 + +在此目录运行以下命令,生成 `dist/DailyFileSync.exe`。 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 +``` + +已安装 .NET 10 或更新版 SDK 的构建机可用以下命令生成三个架构的自包含压缩包。 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\build-standalone.ps1 +``` + +有了自包含压缩包后,使用 Inno Setup 6.3 或更高版本的编译器制作离线安装包。编译器仅用于构建。 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\build-offline-setup.ps1 -Compiler 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' +``` diff --git a/StartupRegistration.cs b/StartupRegistration.cs new file mode 100644 index 0000000..8e38188 --- /dev/null +++ b/StartupRegistration.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Windows.Forms; +using Microsoft.Win32; + +internal static class StartupRegistration +{ + public const string BackgroundArgument = "--background"; + + private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string ValueName = "DailyFileSync"; + + private static string StartupCommand + { + get { return "\"" + Application.ExecutablePath + "\" " + BackgroundArgument; } + } + + public static bool IsEnabled() + { + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunKey)) + { + string command = key == null ? null : key.GetValue(ValueName) as string; + return String.Equals(command, StartupCommand, StringComparison.OrdinalIgnoreCase); + } + } + + public static void SetEnabled(bool enabled) + { + if (enabled) + { + string command = StartupCommand; + if (command.Length > 260) + throw new IOException("程序路径太长,无法设置开机自动启动。请将程序移到路径较短的目录后重试。"); + using (RegistryKey key = Registry.CurrentUser.CreateSubKey(RunKey)) + key.SetValue(ValueName, command, RegistryValueKind.String); + } + else + { + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunKey, true)) + if (key != null) key.DeleteValue(ValueName, false); + } + } +} diff --git a/SyncEngine.cs b/SyncEngine.cs new file mode 100644 index 0000000..6c4860f --- /dev/null +++ b/SyncEngine.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Microsoft.Win32.SafeHandles; + +internal sealed class SyncResult +{ + public int Copied; + public int Unchanged; + public int SkippedLinks; + public int Failed; + public readonly List Errors = new List(); + + public void RecordError(string path, Exception error) + { + Failed++; + if (Errors.Count < 10) + Errors.Add(path + Environment.NewLine + error.Message); + } +} + +internal static class SyncEngine +{ + public static void ValidatePaths(ref string source, ref string destination) + { + source = NormalizeDirectory(source); + destination = NormalizeDirectory(destination); + + if (!Directory.Exists(source)) + throw new IOException("源目录不存在或无法访问。"); + + string resolvedSource = ResolveDirectory(source); + string resolvedDestination = ResolveDirectory(destination); + if (ContainsPath(source, destination) || ContainsPath(destination, source) || + ContainsPath(resolvedSource, resolvedDestination) || ContainsPath(resolvedDestination, resolvedSource)) + throw new IOException("源目录与目标目录必须彼此独立,不能相同或互相包含。"); + } + + public static SyncResult Run(string source, string destination, CancellationToken cancellation) + { + ValidatePaths(ref source, ref destination); + cancellation.ThrowIfCancellationRequested(); + SyncResult result = new SyncResult(); + Stack> directories = new Stack>(); + directories.Push(Tuple.Create(source, destination)); + + while (directories.Count > 0) + { + cancellation.ThrowIfCancellationRequested(); + Tuple pair = directories.Pop(); + try + { + RejectLink(pair.Item1); + RejectLink(pair.Item2); + Directory.CreateDirectory(pair.Item2); + foreach (string entry in Directory.EnumerateFileSystemEntries(pair.Item1)) + { + cancellation.ThrowIfCancellationRequested(); + string target = Path.Combine(pair.Item2, Path.GetFileName(entry)); + try + { + FileAttributes attributes = File.GetAttributes(entry); + if ((attributes & FileAttributes.ReparsePoint) != 0) + result.SkippedLinks++; + else if ((attributes & FileAttributes.Directory) != 0) + directories.Push(Tuple.Create(entry, target)); + else if (CopyIfChanged(entry, target, cancellation)) + result.Copied++; + else + result.Unchanged++; + } + catch (Exception error) + { + if (!IsFileError(error)) throw; + result.RecordError(entry, error); + } + } + } + catch (Exception error) + { + if (!IsFileError(error)) throw; + result.RecordError(pair.Item1 + " → " + pair.Item2, error); + } + } + return result; + } + + private static bool CopyIfChanged(string source, string destination, CancellationToken cancellation) + { + RejectLink(destination); + using (FileStream input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.SequentialScan)) + { + DateTime modified = File.GetLastWriteTimeUtc(source); + FileInfo existing = new FileInfo(destination); + if (existing.Exists && existing.Length == input.Length && existing.LastWriteTimeUtc == modified) + return false; + + string temporary = Path.Combine(Path.GetDirectoryName(destination), ".filesync-" + Guid.NewGuid().ToString("N") + ".tmp"); + bool created = false; + try + { + using (FileStream output = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + created = true; + byte[] buffer = new byte[131072]; + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) != 0) + { + cancellation.ThrowIfCancellationRequested(); + output.Write(buffer, 0, read); + } + } + File.SetLastWriteTimeUtc(temporary, modified); + cancellation.ThrowIfCancellationRequested(); + RejectLink(destination); + if (!MoveFileEx(temporary, destination, 0x1 | 0x8)) // Replace existing file and wait for the move to complete. + throw new Win32Exception(Marshal.GetLastWin32Error()); + created = false; + return true; + } + finally + { + if (created) + { + try { File.Delete(temporary); } + catch (Exception error) { if (!IsFileError(error)) throw; } + } + } + } + } + + private static bool IsFileError(Exception error) + { + return error is IOException || error is UnauthorizedAccessException || error is Win32Exception; + } + + private static string NormalizeDirectory(string path) + { + if (String.IsNullOrWhiteSpace(path)) + throw new ArgumentException("请填写源目录和目标目录。"); + string full = Path.GetFullPath(path.Trim()); + string root = Path.GetPathRoot(full); + return full.Length == root.Length ? root : full.TrimEnd('\\', '/'); + } + + private static bool ContainsPath(string parent, string child) + { + parent = parent.TrimEnd('\\'); + child = child.TrimEnd('\\'); + return child.Equals(parent, StringComparison.OrdinalIgnoreCase) || + child.StartsWith(parent + "\\", StringComparison.OrdinalIgnoreCase); + } + + private static void RejectLink(string path) + { + FileAttributes attributes; + if (TryGetAttributes(path, out attributes) && (attributes & FileAttributes.ReparsePoint) != 0) + throw new IOException("同步路径含有链接或重解析点:" + path); + } + + private static bool TryGetAttributes(string path, out FileAttributes attributes) + { + try + { + attributes = File.GetAttributes(path); + return true; + } + catch (FileNotFoundException) { } + catch (DirectoryNotFoundException) { } + attributes = 0; + return false; + } + + private static string ResolveDirectory(string path) + { + DirectoryInfo directory = new DirectoryInfo(path); + DirectoryInfo existing = null; + Stack missing = new Stack(); + for (DirectoryInfo current = directory; current != null; current = current.Parent) + { + FileAttributes attributes; + if (TryGetAttributes(current.FullName, out attributes)) + { + if ((attributes & FileAttributes.ReparsePoint) != 0) + throw new IOException("同步路径含有链接或重解析点:" + current.FullName); + if ((attributes & FileAttributes.Directory) == 0) + throw new IOException("路径不是目录:" + current.FullName); + if (existing == null) + existing = current; + } + else if (existing == null) + missing.Push(current.Name); + } + if (existing == null) + throw new IOException("目录所在的驱动器或共享无法访问:" + path); + + using (SafeFileHandle handle = CreateFile(existing.FullName, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) + { + if (handle.IsInvalid) + throw new Win32Exception(Marshal.GetLastWin32Error()); + StringBuilder buffer = new StringBuilder(32768); + uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0); + if (length == 0) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (length >= buffer.Capacity) + throw new PathTooLongException(path); + string resolved = buffer.ToString().TrimEnd('\\'); + foreach (string component in missing) + resolved += "\\" + component; + return resolved; + } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool MoveFileEx(string existingFile, string newFile, int flags); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFile(string fileName, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, StringBuilder path, uint size, uint flags); +} diff --git a/SyncSettings.cs b/SyncSettings.cs new file mode 100644 index 0000000..f1e5e19 --- /dev/null +++ b/SyncSettings.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using System.Xml.Serialization; + +public sealed class SyncSettings +{ + private static readonly string SettingsPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "DailyFileSync", "settings.xml"); + private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(SyncSettings)); + + public string Source { get; set; } + public string Destination { get; set; } + public int ScheduledMinute { get; set; } + public DateTime LastScheduledDate { get; set; } + + public SyncSettings() + { + ScheduledMinute = 18 * 60; + } + + internal bool IsConfigured + { + get { return !String.IsNullOrWhiteSpace(Source) && !String.IsNullOrWhiteSpace(Destination); } + } + + internal bool IsDue(DateTime now) + { + return IsConfigured && LastScheduledDate.Date < now.Date && + now.Hour * 60 + now.Minute >= ScheduledMinute; + } + + internal static SyncSettings Load() + { + if (!File.Exists(SettingsPath)) return new SyncSettings(); + + using (FileStream input = File.OpenRead(SettingsPath)) + { + SyncSettings settings = (SyncSettings)Serializer.Deserialize(input); + if (settings.ScheduledMinute < 0 || settings.ScheduledMinute >= 24 * 60) + throw new IOException("保存的同步时间无效。"); + return settings; + } + } + + internal void Save() + { + string directory = Path.GetDirectoryName(SettingsPath); + Directory.CreateDirectory(directory); + string temporary = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".tmp"); + try + { + using (FileStream output = new FileStream(temporary, FileMode.CreateNew)) + Serializer.Serialize(output, this); + + if (File.Exists(SettingsPath)) + File.Replace(temporary, SettingsPath, null); + else + File.Move(temporary, SettingsPath); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } +} diff --git a/app.manifest b/app.manifest new file mode 100644 index 0000000..88123f2 --- /dev/null +++ b/app.manifest @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + true + + + diff --git a/build-offline-setup.ps1 b/build-offline-setup.ps1 new file mode 100644 index 0000000..52f6250 --- /dev/null +++ b/build-offline-setup.ps1 @@ -0,0 +1,44 @@ +param( + [Parameter(Mandatory = $true)] + [string] $Compiler, + + [ValidateSet('win-x64', 'win-x86', 'win-arm64')] + [string[]] $Architecture = @('win-x64', 'win-x86', 'win-arm64') +) + +$ErrorActionPreference = 'Stop' +$compilerPath = (Resolve-Path -LiteralPath $Compiler).ProviderPath +$dist = Join-Path $PSScriptRoot 'dist' +$setup = Join-Path $PSScriptRoot 'OfflineSetup.iss' +$staging = Join-Path $PSScriptRoot 'obj\offline-setup' +$supportedSystems = @{ 'win-x64' = 'x64os'; 'win-x86' = 'x86compatible'; 'win-arm64' = 'arm64' } +New-Item -ItemType Directory -Path $staging -Force | Out-Null +$staging = (Resolve-Path -LiteralPath $staging).ProviderPath +Add-Type -AssemblyName System.IO.Compression.FileSystem + +foreach ($runtime in $Architecture) { + $portable = "DailyFileSync-standalone-$runtime" + $archive = Join-Path $dist "$portable.zip" + if (-not (Test-Path -LiteralPath $archive -PathType Leaf)) { + throw "Missing $archive. Run build-standalone.ps1 first." + } + + $workingDirectory = Join-Path $staging ([guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $workingDirectory | Out-Null + try { + [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $workingDirectory) + $payload = Join-Path $workingDirectory $portable + $package = "DailyFileSync-Offline-Setup-$runtime" + & $compilerPath /Qp "/DPayloadPath=$payload" "/DPackageArchitecture=$($supportedSystems[$runtime])" "/DPackageName=$package" "/O$dist" $setup + if ($LASTEXITCODE -ne 0) { + throw "Installer compilation failed for $runtime with exit code $LASTEXITCODE." + } + + Write-Output (Join-Path $dist "$package.exe") + } finally { + $resolvedDirectory = (Resolve-Path -LiteralPath $workingDirectory).ProviderPath + if ((Split-Path -Parent $resolvedDirectory) -eq $staging) { + Remove-Item -LiteralPath $resolvedDirectory -Recurse -Force + } + } +} diff --git a/build-standalone.ps1 b/build-standalone.ps1 new file mode 100644 index 0000000..00b4d12 --- /dev/null +++ b/build-standalone.ps1 @@ -0,0 +1,37 @@ +param( + [ValidateSet('win-x64', 'win-x86', 'win-arm64')] + [string[]] $Architecture = @('win-x64', 'win-x86', 'win-arm64') +) + +$ErrorActionPreference = 'Stop' +$project = Join-Path $PSScriptRoot 'DailyFileSync.csproj' +$dist = Join-Path $PSScriptRoot 'dist' +$staging = Join-Path $PSScriptRoot 'obj\standalone' +New-Item -ItemType Directory -Path $dist, $staging -Force | Out-Null +$staging = (Resolve-Path -LiteralPath $staging).ProviderPath +Add-Type -AssemblyName System.IO.Compression.FileSystem + +foreach ($runtime in $Architecture) { + $package = "DailyFileSync-standalone-$runtime" + $workingDirectory = Join-Path $staging ([guid]::NewGuid().ToString('N')) + $publishDirectory = Join-Path $workingDirectory $package + $stagedArchive = Join-Path $workingDirectory "$package.zip" + $archive = Join-Path $dist "$package.zip" + New-Item -ItemType Directory -Path $workingDirectory | Out-Null + + try { + & dotnet publish $project --configuration Release --runtime $runtime --self-contained true --output $publishDirectory -p:DebugType=none + if ($LASTEXITCODE -ne 0) { + throw "Publishing failed for $runtime. See the dotnet output above." + } + + [System.IO.Compression.ZipFile]::CreateFromDirectory($publishDirectory, $stagedArchive, [System.IO.Compression.CompressionLevel]::Optimal, $true) + Move-Item -LiteralPath $stagedArchive -Destination $archive -Force + Write-Output $archive + } finally { + $resolvedDirectory = (Resolve-Path -LiteralPath $workingDirectory).ProviderPath + if ((Split-Path -Parent $resolvedDirectory) -eq $staging) { + Remove-Item -LiteralPath $resolvedDirectory -Recurse -Force + } + } +} diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..5fd4aaa --- /dev/null +++ b/build.ps1 @@ -0,0 +1,24 @@ +$ErrorActionPreference = 'Stop' + +$framework = Join-Path $env:WINDIR 'Microsoft.NET\Framework\v4.0.30319' +$compiler = Join-Path $framework 'csc.exe' +if (-not (Test-Path -LiteralPath $compiler -PathType Leaf)) { + throw 'The .NET Framework C# compiler was not found.' +} + +$outputDirectory = Join-Path $PSScriptRoot 'dist' +New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null +$output = Join-Path $outputDirectory 'DailyFileSync.exe' +$manifest = Join-Path $PSScriptRoot 'app.manifest' +$sources = 'Program.cs', 'MainForm.cs', 'StartupRegistration.cs', 'SyncSettings.cs', 'SyncEngine.cs' | ForEach-Object { + Join-Path $PSScriptRoot $_ +} + +& $compiler /nologo /target:winexe /platform:anycpu /optimize+ /codepage:65001 ` + /reference:System.Windows.Forms.dll /reference:System.Drawing.dll ` + "/win32manifest:$manifest" "/out:$output" @sources +if ($LASTEXITCODE -ne 0) { + throw "Compilation failed with exit code $LASTEXITCODE." +} + +Write-Output $output