简体   繁体   中英

FileSystemWatcher - On Delete, copy a file

I have a question, I am creating a FileWatcher to monitor a folder, and I am trying to create a method that copies the deleted file from another location.

It is this possible using the FileSystemEventHandler?

Alternatively, in last case, can I restrict the folder to changes with the FileSystemWatcher?

Thanks.

Your code should be something along the lines of the following:

using System.IO;

//...

const string SourceDirectory = @"\\myServer\share\originalFiles";
private static void OnDeleted (object source, FileSystemEventArgs e)
{

    //this will help prove if the fsw is being triggered / whether the error's in your copy file piece or due to the trigger not firing
    Debug.WriteLine(e.FullPath);
    Debug.WriteLine(e.ChangeType);

    var filename = e.Name; //NB: Returns path relative to the monitored folder; e.g. if monitoring "c:\demo" and file "c:\demo\something\file.txt" is changed, would return "something\file.txt"
    //var filename = Path.GetFilename(e.FullPath); //if you don't want the above behaviour, given the same scenario this would return "file.txt" instead
    var sourceFilename = Path.Combine(SourceDirectory, filename);

    /* not sure if this is required: see https://github.com/Microsoft/dotnet/issues/437
    while (File.Exists(e.FullPath)) { //just in case the delete operation is still in progress when this code's triggered.
        Threading.Thread.Sleep(500);
    }
    */

    File.Copy(sourceFilename, e.FullPath);
}

//...

const string MonitoredDirectory = @"\\myServer\share\watchedFiles\";
public static void Main(string[] args) {
    FileSystemWatcher fsw = new FileSystemWatcher();
    fsw.Path = MonitoredDirectory;
    fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    //fsw.Filter = "*.xml"; //add something like this if you want to filter on certain file extensions / that sort of thing 
    fsw.OnDeleted += new FileSystemEventHandler(OnDeleted);
    fsw.EnableRaisingEvents = true;
    Console.WriteLine("This monitor will now run until you press 'x' (i.e. as we need to keep the program running to keep the fsw in operation)");
    while(Console.Read() != 'x');
}

(the above is untested)

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