-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectoryManager.cs
53 lines (43 loc) · 1.66 KB
/
DirectoryManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.IO;
namespace SaveFileWatcher
{
public class DirectoryWatcher(string directoryPath, string backupDirectoryPath)
{
private readonly string _directoryPath = directoryPath;
private readonly string _backupDirectoryPath = backupDirectoryPath;
public void StartWatching()
{
FileSystemWatcher watcher = new(_directoryPath)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName
};
watcher.Changed += OnFileChanged;
watcher.Created += OnFileChanged;
watcher.Deleted += OnFileChanged;
watcher.Renamed += OnFileChanged;
watcher.EnableRaisingEvents = true;
Console.WriteLine($"Watching directory: {_directoryPath}");
Console.WriteLine($"Backup directory: {_backupDirectoryPath}");
Console.WriteLine("Press any key to stop watching...");
Console.ReadKey();
watcher.EnableRaisingEvents = false;
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
string sourceFilePath = e.FullPath;
string destinationFilePath = Path.Combine(_backupDirectoryPath, e.Name!);
try
{
File.Copy(sourceFilePath, destinationFilePath, true);
Console.WriteLine($"File backed up: {e.Name}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to back up file: {e.Name}");
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}