superstar_v2/DataCheck.cs
jasonchenwork 8f456c347d 調整 video 開啓先比對
新增 env 多個遠端路徑
新増 env 能比對檔案路徑
20250704
2025-07-04 14:45:39 +08:00

81 lines
2.7 KiB
C#

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