using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace DataCheck { public class DataChecker { public DataChecker() { // 加入你要同步的資料夾 SyncFolder(Utils.Env.GetPath("video", ""), @"D:\video", "video", new[] { ".mpg" }); } private void SyncFolder(string serverPath, string localPath, string label, string[] extensions) { if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } if (!Directory.Exists(serverPath)) { Console.WriteLine($"找不到伺服器資料夾:{serverPath}"); return; } var serverFiles = Directory.GetFiles(serverPath) .Where(f => extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase)) .Select(f => new FileInfo(f)) .ToDictionary(f => f.Name, f => f); var localFiles = Directory.GetFiles(localPath) .Where(f => extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase)) .Select(f => new FileInfo(f)) .ToDictionary(f => f.Name, f => f); // 1. 複製或更新檔案 foreach (var serverFile in serverFiles) { bool needsCopy = !localFiles.ContainsKey(serverFile.Key) || serverFile.Value.LastWriteTime > localFiles[serverFile.Key].LastWriteTime; if (needsCopy) { try { string dest = Path.Combine(localPath, serverFile.Key); File.Copy(serverFile.Value.FullName, dest, true); Console.WriteLine($"更新{label}: {serverFile.Key}"); } catch (Exception ex) { Console.WriteLine($"複製{label}失敗 {serverFile.Key}: {ex.Message}"); } } } // 2. 刪除多餘的本地檔案 foreach (var localFile in localFiles) { if (!serverFiles.ContainsKey(localFile.Key)) { try { File.Delete(localFile.Value.FullName); Console.WriteLine($"刪除多餘{label}: {localFile.Key}"); } catch (Exception ex) { Console.WriteLine($"刪除{label}失敗 {localFile.Key}: {ex.Message}"); } } } } } }