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); }