superstar_v2/DataCheck.cs
2025-06-24 10:35:01 +08:00

140 lines
5.4 KiB
C#

using System.IO;
namespace DataCheck
{
public class dataCheck
{
public dataCheck()
{
menu_check();
news_check();
}
private void menu_check()
{
string menuPath = @"\\svr01\foods";
string menuPath_local = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "foods");
if (!Directory.Exists(menuPath_local))
{
Directory.CreateDirectory(menuPath_local);
}
var serverFiles = Directory.GetFiles(menuPath, "*.jpg")
.Select(f => new FileInfo(f))
.ToDictionary(f => f.Name, f => f);
var localFiles = Directory.GetFiles(menuPath_local, "*.jpg")
.Select(f => new FileInfo(f))
.ToDictionary(f => f.Name, f => f);
foreach (var serverFile in serverFiles)
{
bool needsCopy = false;
string localFilePath = Path.Combine(menuPath_local, serverFile.Key);
if (!localFiles.ContainsKey(serverFile.Key))
{
needsCopy = true;
}
else
{
var localFile = localFiles[serverFile.Key];
if (serverFile.Value.LastWriteTime > localFile.LastWriteTime)
{
needsCopy = true;
}
}
if (needsCopy)
{
try
{
File.Copy(serverFile.Value.FullName, localFilePath, true);
Console.WriteLine($"更新菜單: {serverFile.Key}");
}
catch (Exception ex)
{
Console.WriteLine($"複製菜單失敗 {serverFile.Key}: {ex.Message}");
}
}
}
// 3-2. 清除本地有但伺服器已經沒有的檔案
foreach (var localFile in localFiles)
{
if (!serverFiles.ContainsKey(localFile.Key))
{
try
{
File.Delete(localFile.Value.FullName);
Console.WriteLine($"刪除本地多餘菜單: {localFile.Key}");
}
catch (Exception ex)
{
Console.WriteLine($"刪除菜單失敗 {localFile.Key}: {ex.Message}");
}
}
}
}
private void news_check()
{
string newsPath = @"\\svr01\news";
string newsPath_local = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "news");
if (!Directory.Exists(newsPath_local))
{
Directory.CreateDirectory(newsPath_local);
}
var serverFiles = Directory.GetFiles(newsPath, "*.jpg")
.Select(f => new FileInfo(f))
.ToDictionary(f => f.Name, f => f);
var localFiles = Directory.GetFiles(newsPath_local, "*.jpg")
.Select(f => new FileInfo(f))
.ToDictionary(f => f.Name, f => f);
foreach (var serverFile in serverFiles)
{
bool needsCopy = false;
string localFilePath = Path.Combine(newsPath_local, serverFile.Key);
if (!localFiles.ContainsKey(serverFile.Key))
{
needsCopy = true;
}
else
{
var localFile = localFiles[serverFile.Key];
if (serverFile.Value.LastWriteTime > localFile.LastWriteTime)
{
needsCopy = true;
}
}
if (needsCopy)
{
try
{
File.Copy(serverFile.Value.FullName, localFilePath, true);
Console.WriteLine($"更新新聞: {serverFile.Key}");
}
catch (Exception ex)
{
Console.WriteLine($"複製新聞失敗 {serverFile.Key}: {ex.Message}");
}
}
}
// 3-2. 清除本地有但伺服器已經沒有的檔案
foreach (var localFile in localFiles)
{
if (!serverFiles.ContainsKey(localFile.Key))
{
try
{
File.Delete(localFile.Value.FullName);
Console.WriteLine($"刪除本地多餘新聞: {localFile.Key}");
}
catch (Exception ex)
{
Console.WriteLine($"刪除新聞失敗 {localFile.Key}: {ex.Message}");
}
}
}
}
}
}