简体   繁体   中英

FileSystemWatcher File.Copy

I would like to watch a directory for changes made to files and copy the files to a new destination when the event gets triggered. How do I call a File.Copy method as the action to get triggered? below is the code I currently have.

 static void Main(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(@"F:\IOP\EW\02_Plant\03_Design\01_Models\2210-Sec Crushing");

        // Begin watching.
        watcher.Filter = "0-EW*.dgn";
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;

        watcher.Changed += Watcher_Changed;
        watcher.Created += Watcher_Created;
        watcher.Deleted += Watcher_Deleted;
        watcher.Renamed += Watcher_Renamed;

        Console.Read(); // don't forget to stop the program at this line


    }

    private static void Watcher_Renamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine("File: {0} renamed to {1} at time {2}",e.OldName,e.Name,DateTime.Now.ToLocalTime());
    }

    private static void Watcher_Deleted(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("File: {0} deleted at time: {1}", e.Name, DateTime.Now.ToLocalTime());
    }

    private static void Watcher_Created(object sender, FileSystemEventArgs e)

    {
        Console.WriteLine("File: {0} created at time: {1}", e.Name, DateTime.Now.ToLocalTime());
    }

    private static void Watcher_Changed(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("File: {0} changed at time: {1}", e.Name, DateTime.Now.ToLocalTime());        
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        //Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }

You have the Path and the file name in the triggered event arguments:

private static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
   File.Copy(e.FullPath, Path.Combine("D:\\Backup", e.Name));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM