Код: Выделить всё
[Test]
public void CreateFile_ShouldUpdateTree_Simple()
{
// Arrange
_watcher = new DirectoryTreeWatcher(_testRootPath);
int eventTriggered = 0;
_watcher.OnChanged += (e) => { Interlocked.Increment(ref eventTriggered); };
// Act
string newFile = Path.Combine(_testRootPath, "newFile.txt");
File.WriteAllText(newFile, "newContent");
// Wait for event
Thread.Sleep(500);
// Assert
Assert.IsTrue(eventTriggered > 0, "OnChanged event was not triggered");
}
Код: Выделить всё
public DirectoryTreeWatcher(string path)
{
if (!Directory.Exists(path))
{
throw new DirectoryNotFoundException($"Directory not found: {path}");
}
InitializeWatcher(path);
_root = ScanDirectory(path);
}
void InitializeWatcher(string rootPath)
{
_rootPath = rootPath;
_watcher = new FileSystemWatcher(rootPath, "");
_watcher.InternalBufferSize = 64 * 1024;
_watcher.NotifyFilter = NotifyFilters.FileName
| NotifyFilters.DirectoryName
| NotifyFilters.LastWrite;
_watcher.Error += (o, e) => OnChanged?.Invoke(new ChangeEvent(e.GetException()));
_watcher.Changed += (o, e) => OnChanged?.Invoke(new ChangeEvent(WatcherChangeTypes.Changed, e.FullPath));
_watcher.Created += (o, e) => OnChanged?.Invoke(new ChangeEvent(WatcherChangeTypes.Created, e.FullPath));
_watcher.Deleted += (o, e) => OnChanged?.Invoke(new ChangeEvent(WatcherChangeTypes.Deleted, e.FullPath));
_watcher.Renamed += (o, e) => OnChanged?.Invoke(new ChangeEvent(WatcherChangeTypes.Renamed, e.FullPath, e.OldFullPath));
_watcher.IncludeSubdirectories = true;
_watcher.EnableRaisingEvents = true;
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... t-randomly
Мобильная версия