我想查看目录中对文件所做的更改,并在触发事件时将文件复制到新的目的地。如何将File.Copy方法称为要触发的动作?下面是我当前拥有的代码。
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}");
}
答案 0 :(得分:0)
在触发的事件参数中具有路径和文件名:
private static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, Path.Combine("D:\\Backup", e.Name));
}