FileSystemWatcher - 在删除时复制文件

时间:2017-07-10 16:05:22

标签: c# filesystemwatcher

我有一个问题,我正在创建一个FileWatcher来监控文件夹,我正在尝试创建一个从其他位置复制已删除文件的方法。

使用FileSystemEventHandler可以吗?

或者,在最后一种情况下,我可以使用FileSystemWatcher将文件夹限制为更改吗?

感谢。

1 个答案:

答案 0 :(得分:0)

您的代码应该符合以下内容:

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');
}

(以上未经测试)