解决方案1:使用文件系统监视器进行同步
using System.IO;
class Program
{
static void Main()
{
string sourceDirectory = "path/to/source/directory";
string targetDirectory = "path/to/target/directory";
// 创建文件系统监视器
FileSystemWatcher watcher = new FileSystemWatcher(sourceDirectory);
// 监视文件的更改、创建或删除事件
watcher.NotifyFilter = NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// 设置事件处理方法
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// 开始监视
watcher.EnableRaisingEvents = true;
// 阻止程序退出
Console.ReadLine();
}
// 文件更改、创建和删除事件处理方法
private static void OnChanged(object source, FileSystemEventArgs e)
{
string sourceFilePath = e.FullPath;
string targetFilePath = "path/to/target/directory" + e.Name;
// 拷贝文件到目标目录
File.Copy(sourceFilePath, targetFilePath, true);
}
// 文件重命名事件处理方法
private static void OnRenamed(object source, RenamedEventArgs e)
{
string sourceFilePath = e.FullPath;
string targetFilePath = "path/to/target/directory" + e.Name;
// 将目标目录下的旧文件名更改为新文件名
File.Move(sourceFilePath, targetFilePath);
}
}
解决方案2:使用定时任务进行同步
using System.IO;
using System.Threading;
class Program
{
static void Main()
{
string sourceDirectory = "path/to/source/directory";
string targetDirectory = "path/to/target/directory";
// 创建定时任务,每隔一段时间执行同步操作
Timer timer = new Timer(SyncFiles, null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
// 阻止程序退出
Console.ReadLine();
}
// 文件同步方法
private static void SyncFiles(object state)
{
string sourceDirectory = "path/to/source/directory";
string targetDirectory = "path/to/target/directory";
// 获取源目录中的所有文件
string[] sourceFiles = Directory.GetFiles(sourceDirectory);
foreach (string sourceFilePath in sourceFiles)
{
string fileName = Path.GetFileName(sourceFilePath);
string targetFilePath = Path.Combine(targetDirectory, fileName);
// 拷贝文件到目标目录
File.Copy(sourceFilePath, targetFilePath, true);
}
}
}
以上两种解决方案都可以实现将位于不同目录下的文件相互同步。你可以根据实际需求选择其中一种来实现。