C# Monitor and transfer or copy the changed or created file to a new location
阅读原文时间:2023年07月11日阅读:2

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
MonitorAndTransferFiles();
Console.ReadLine();
}

    static string destPath = @"D:\\C\\ConsoleApplication2\\ConsoleApplication2";

    static void MonitorAndTransferFiles(string sourcePath=null)  
    {  
        sourcePath = Directory.GetCurrentDirectory();  
        WatchFiles(sourcePath);  
    }       

    static void WatchFiles(string path)  
    {  
        FileSystemWatcher watcher = new FileSystemWatcher();  
        watcher.Path = path;  
        watcher.NotifyFilter = NotifyFilters.LastWrite|NotifyFilters.CreationTime;  
        watcher.Filter = "\*.\*";  
        watcher.Changed += Watcher\_Changed;  
        watcher.Created += Watcher\_Created;  
        watcher.EnableRaisingEvents = true;  
    }

    private static void Watcher\_Created(object sender, FileSystemEventArgs e)  
    {  
        try  
        {  
            Console.WriteLine($"Created:FullPath:{e.FullPath}, ChangeType: {e.ChangeType}");  
            File.Copy(e.FullPath, Path.Combine(destPath, Path.GetFileName(e.FullPath)), true);  
        }  
        catch  
        {  
        }  
    }

    private static void Watcher\_Changed(object sender, FileSystemEventArgs e)  
    {  
        try  
        {  
            Console.WriteLine($"Changed:FullPath:{e.FullPath}, ChangeType: {e.ChangeType}");  
            File.Copy(e.FullPath, Path.Combine(destPath, Path.GetFileName(e.FullPath)), true);  
        }  
        catch  
        {  
        }

    }  
}  

}