public static FileSystemWatcher OnFileChanged(this string filePath, Action onFileChanged) { if (filePath.IsBlank()) { throw Fault.NullRef("filePath"); } if (!File.Exists(filePath)) { throw Fault.MissingFile(filePath); } var abs = filePath.MakeAbsolute(); var dir = Path.GetDirectoryName(abs); var nme = Path.GetFileName(abs); var watchr = new FileSystemWatcher(dir, nme); watchr.NotifyFilter = NotifyFilters.LastWrite; watchr.Changed += (s, e) => { try { onFileChanged?.Invoke(); } catch (Exception ex) { Alert.Show(ex, "OnFileChanged"); } }; watchr.EnableRaisingEvents = true; return(watchr); }
private void InitializeFileWatcher() { if (WatchedFile.IsBlank()) { throw Fault.NullRef(nameof(WatchedFile)); } if (!File.Exists(WatchedFile)) { throw Fault.MissingFile(WatchedFile); } var abs = WatchedFile.MakeAbsolute(); var dir = Path.GetDirectoryName(abs); var nme = Path.GetFileName(abs); _watchr = new FileSystemWatcher(dir, nme); _watchr.NotifyFilter = NotifyFilters.LastWrite; _watchr.Changed += async(s, e) => { if (!_isDelaying) { _isDelaying = true; await Task.Delay(1000); IsFileChanged = true; OnFileChanged(); _isDelaying = false; } }; _watchr.EnableRaisingEvents = true; }
public static bool FileContains(this string filePath, string text) { if (!File.Exists(filePath)) { throw Fault.MissingFile(filePath); } return(File.ReadLines(filePath).ToList() .Any(_ => _.Contains(text))); }