欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Monitor and transfer or copy the changed or created file to a new location

程序员文章站 2022-04-14 19:45:22
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diag... ......
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
            {
            }
            
        } 
    }
}