internal static IDocument GetDocument(string fullPath, FileSystemEventHandler fileDeletedCallback = null) { if (string.IsNullOrWhiteSpace(fullPath)) { return null; } var fileName = fullPath.ToLowerInvariant(); IDocument currentDocument; if (DocumentLookup.TryGetValue(fileName, out currentDocument)) { return currentDocument; } var factory = GetFactory(fileName); if (factory == null) { return null; } currentDocument = factory(fullPath, fileDeletedCallback); if (currentDocument == null) { return null; } return DocumentLookup.AddOrUpdate(fileName, x => currentDocument, (x, e) => currentDocument); }
void CreateWatch(string dirPath, FileSystemEventHandler handler) { if (_watchers.ContainsKey(dirPath)) { _watchers[dirPath].Dispose(); _watchers[dirPath] = null; } if (!Directory.Exists(dirPath)) return; var watcher = new FileSystemWatcher(); watcher.IncludeSubdirectories = false;//includeSubdirectories; watcher.Path = dirPath; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size; watcher.Filter = "*"; watcher.Changed += handler; watcher.EnableRaisingEvents = true; watcher.InternalBufferSize = 10240; //return watcher; _watchers[dirPath] = watcher; foreach (var childDirPath in Directory.GetDirectories(dirPath)) { CreateWatch(childDirPath, handler); } }
private void InitFormOnce() { cboProfile.SelectedIndexChanged += new EventHandler(cboProfile_SelectedIndexChanged); _textFileChangedHandler = new FileSystemEventHandler(_host_TextFileChanged); _host.TextFileChanged += _textFileChangedHandler; LoadProfiles(); PluginUtils.InitPluginGrid(dgvPlugin); #region Init values nudLoopCount.Value = Config.DeobfFlowOptionBranchLoopCount; nudMaxRefCount.Value = Config.DeobfFlowOptionMaxRefCount; txtRegex.Text = Config.LastRegex; InitBranchDirection(cboDirection); if (Config.DeobfFlowOptionBranchDirection >= 0 && Config.DeobfFlowOptionBranchDirection < cboDirection.Items.Count) { cboDirection.SelectedIndex = Config.DeobfFlowOptionBranchDirection; } else { cboDirection.SelectedIndex = 0; } #endregion }
public void SetChangedHandler(FileSystemEventHandler handler) { if (_fileWatcher != null) { _fileWatcher.Changed += handler; } }
public void RemoveChangedHandler(FileSystemEventHandler handler) { if (_fileWatcher != null) { _fileWatcher.Changed -= handler; } }
public FileWatcher(string filepath, FileChangedHandler handler) : base(System.IO.Path.GetDirectoryName(filepath), System.IO.Path.GetFileName(filepath)) { FilePath = filepath; Handler = handler; NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; Changed += new FileSystemEventHandler(delegate(object sender, FileSystemEventArgs e) { // TODO : Find alternative !! /* System.Windows.Application.Current.Dispatcher.BeginInvoke( new VoidDelegate(this.FileChanged)); */ }); UpdateFileInfo(); Timer = new Timer(100); Timer.AutoReset = false; Timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e) { // TODO : Find alternative !! /* System.Windows.Application.Current.Dispatcher.BeginInvoke( new VoidDelegate(this.TimerElapsed)); */ }); EnableRaisingEvents = true; }
internal FileChangeEventTarget(string fileName, OnChangedCallback onChangedCallback) { _fileName = fileName; _onChangedCallback = onChangedCallback; _changedHandler = new FileSystemEventHandler(this.OnChanged); _errorHandler = new ErrorEventHandler(this.OnError); _renamedHandler = new RenamedEventHandler(this.OnRenamed); }
/// <summary> /// Will create a FileSystemWatcher on every directory, including and contained in the directory passed in /// </summary> /// <param name="basepath">directory path</param> /// <param name="handler">Method, signature must accept object, FileSystemEventArgs</param> public FileWacher(string basepath, FileSystemEventHandler handler) { _basepath = basepath; _watchers = new List<FileSystemWatcher>(); _handler = handler; BuildWatchers(_basepath); }
public static FileSystemWatcher OnChangeOrCreation(this FileSystemWatcher watcher, FileSystemEventHandler handler) { watcher.Changed += handler; watcher.Created += handler; return watcher; }
public dynFileReader() { handler = new FileSystemEventHandler(watcher_FileChanged); InPortData.Add(new PortData("path", "Path to the file", typeof(string))); OutPortData.Add(new PortData("contents", "File contents", typeof(string))); NodeUI.RegisterAllPorts(); }
public FileReader() { handler = watcher_FileChanged; InPortData.Add(new PortData("path", "Path to the file", typeof(string))); OutPortData.Add(new PortData("contents", "File contents", typeof(string))); RegisterAllPorts(); }
public dynFileReader() { this.handler = new FileSystemEventHandler(watcher_FileChanged); InPortData.Add(new PortData("path", "Path to the file", typeof(string))); OutPortData = new PortData("contents", "File contents", typeof(string)); base.RegisterInputsAndOutputs(); }
public FileSystemWatcherOptions(string path, string filter, FileSystemEventHandler changedAction, FileSystemEventHandler createdAction, ErrorEventHandler errorAction, FileSystemEventHandler deletedAction, RenamedEventHandler renamedAction) { Path = path; Filter = filter; ChangedAction = changedAction; CreatedAction = createdAction; ErrorAction = errorAction; DeletedAction = deletedAction; RenamedAction = renamedAction; }
/// <summary> /// Create watcher for the specified file and monitor changes /// </summary> /// <param name="file_changed_func"></param> public FileWatcher(FileSystemEventHandler file_changed_func) { watcher = new FileSystemWatcher(); watcher.Path = Config.get_game_path(); //Always check the last write to the file watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Filter = "Chat.log"; //Callback watcher.Changed += new FileSystemEventHandler(file_changed_func); //Start watching watcher.EnableRaisingEvents = true; }
public WrapFileDescriptor(string path, IWrapRepository wraps, FileSystemEventHandler handler) { Repository = wraps; Clients = new List<IWrapAssemblyClient>(); FilePath = path; FileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path)) { NotifyFilter = NotifyFilters.LastWrite }; FileSystemWatcher.Changed += handler; FileSystemWatcher.EnableRaisingEvents = true; }
public WatchedFile(string filePath, FileSystemEventHandler eventHandler) : base(filePath) { string fileName = Path.GetFileName(ResourcePath); string directoryPath = Path.GetDirectoryName(ResourcePath); _watcher = new FileSystemWatcher(directoryPath, fileName); _watcher.Changed += OnWatcherEvent; _watcher.NotifyFilter = NotifyFilters.LastWrite; _watcher.EnableRaisingEvents = true; AddHandler(eventHandler); }
/// <summary> /// Watches a folder for folder creation /// </summary> /// <param name="path">Which folder or fileshare to watch</param> /// <param name="actionOnFolderCreated">Action to perform when a change is detected. The action is invoked asynchronosly</param> public FolderChangeWatcher(string path, FileSystemEventHandler actionOnFolderCreated) { if (actionOnFolderCreated == null) throw new ArgumentNullException("actionOnFolderCreated"); _actionOnFolderCreated = actionOnFolderCreated; _watcher = new FileSystemWatcher(path); _watcher.Created += OnFolderCreated; _watcher.InternalBufferSize = 16384; //16KB buffer instead of 4KB (default). _watcher.IncludeSubdirectories = false; _watcher.EnableRaisingEvents = true; }
/// <summary> /// Watches a folder for file changes matching filter /// </summary> /// <param name="path">Which folder or fileshare to watch</param> /// <param name="fileFilter">Which files to wathc for, ex *.txt</param> /// <param name="actionOnFileChanged">Action to perform when a change is detected. The action is invoked asynchronosly</param> /// <param name="filter">Which changes to act upon</param> public FileChangeWatcher(string path, string fileFilter, FileSystemEventHandler actionOnFileChanged, NotifyFilters filter) { if (actionOnFileChanged == null) throw new ArgumentNullException("actionOnFileChanged"); _actionOnFileChanged = actionOnFileChanged; _watcher = new FileSystemWatcher(path, fileFilter); _watcher.Changed += OnFileChanged; _watcher.InternalBufferSize = 16384; //16KB buffer instead of 4KB (default). _watcher.NotifyFilter = filter; _watcher.IncludeSubdirectories = false; _watcher.EnableRaisingEvents = true; }
static Watcher() { Watchers = new ConcurrentDictionary<String, WatcherInfo>(); FileWatchersFactory = ProduceFileWatcher; DirectoryWatchersFactory = ProduceDirectoryWatcher; FileCreatedOrChangedHandler = HandleFileCreatedOrChanged; FileDeletedHandler = HandleFileDeleted; FileRenamedHandler = HandleFileRenamed; FileWatchingErrorHandler = HandleFileWatchingError; DirectoryWatchingErrorHandler = HandleDirectoryWatchingError; FileInDirectoryRenamedHandler = HandleFileInDirectoryRenamed; }
public static void WatchFiles(string path, string filter, FileSystemEventHandler handler) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.IncludeSubdirectories = true; watcher.Filter = filter; watcher.Path = path; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size; watcher.Created += handler; watcher.Changed += handler; watcher.Deleted += handler; watcher.EnableRaisingEvents = true; }
public static void FileSystemWatcher_Deleted() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Deleted += handler; watcher.Deleted -= handler; // shouldn't throw watcher.Deleted -= handler; } }
public void FileSystemWatcher_Deleted() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Deleted += handler; watcher.Deleted -= handler; // shouldn't throw watcher.Deleted -= handler; } }
public static CancellationToken GetShutdownCancellationToken(ILogger logger = null) { if (_jobShutdownCancellationTokenSource != null) { return(_jobShutdownCancellationTokenSource.Token); } lock (_lock) { if (_jobShutdownCancellationTokenSource != null) { return(_jobShutdownCancellationTokenSource.Token); } _jobShutdownCancellationTokenSource = new CancellationTokenSource(); Console.CancelKeyPress += (sender, args) => { _jobShutdownCancellationTokenSource.Cancel(); if (logger != null & logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Job shutdown event signaled: {SpecialKey}", args.SpecialKey); } args.Cancel = true; }; string webJobsShutdownFile = Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE"); if (String.IsNullOrEmpty(webJobsShutdownFile)) { return(_jobShutdownCancellationTokenSource.Token); } var handler = new FileSystemEventHandler((s, e) => { if (e.FullPath.IndexOf(Path.GetFileName(webJobsShutdownFile), StringComparison.OrdinalIgnoreCase) < 0) { return; } _jobShutdownCancellationTokenSource.Cancel(); logger?.LogInformation("Job shutdown signaled."); }); var watcher = new FileSystemWatcher(Path.GetDirectoryName(webJobsShutdownFile)); watcher.Created += handler; watcher.Changed += handler; watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.IncludeSubdirectories = false; watcher.EnableRaisingEvents = true; return(_jobShutdownCancellationTokenSource.Token); } }
/** * Utility method that calls the specified argument functions whenever League starts or stops. * This is done by observing the lockfile, and the start function gets the contents of the lockfile as a param. */ public static void MonitorLeague(string lcuExecutablePath, Action <string> onStart, Action onStop) { var leagueDir = Path.GetDirectoryName(lcuExecutablePath) + "\\"; var watcher = new FileSystemWatcher(); watcher.Path = leagueDir; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastAccess; watcher.Filter = "lockfile"; var active = false; // We use the same handler for both lockfile creation and lockfile edits. // Sometimes we are so fast that the file is still empty when we attempt to read it. // This way, it will be caught in the edit event instead. FileSystemEventHandler createdEditHandler = (o, e) => { if (active) { return; } var contents = ReadLockfile(leagueDir); if (!contents.Equals("")) { onStart(contents); active = true; } }; watcher.Created += createdEditHandler; watcher.Changed += createdEditHandler; watcher.Deleted += (o, e) => { // Lockfile was deleted, notify. onStop(); active = false; }; watcher.EnableRaisingEvents = true; // Check if we launched while league was already active. if (File.Exists(leagueDir + "\\lockfile")) { active = true; onStart(ReadLockfile(leagueDir)); } }
private void Start() { Logger = base.Logger; IsVerbose = Config.Bind("Heelz", "Heelz Verbose Mode", false, new ConfigDescription("Make Heelz Plugin print all of debug messages in console. Useless for most of users.")); LoadDevXML = Config.Bind("Heelz", "Load Developer XML", false, new ConfigDescription("Make Heelz Plugin load heel_manifest.xml file from game root folder. Useful for developing heels. Useless for most of users.")); CharacterApi.RegisterExtraBehaviour <HeelsController>(GUID); HarmonyWrapper.PatchAll(typeof(HeelPlugin)); Logger.LogInfo("[Heelz] Heels mode activated: destroy all foot"); var loadedManifests = Sideloader.Sideloader.Manifests.Values; foreach (var manifest in loadedManifests) { LoadXML(manifest.manifestDocument); } if (LoadDevXML.Value) { try { string rootPath = Directory.GetParent(Application.dataPath).ToString(); string devXMLPath = rootPath + "/heel_manifest.xml"; if (File.Exists(devXMLPath)) { Log("Development File Detected! Updating heels as soon as it's getting updated!"); FileSystemWatcher fsWatcher = new FileSystemWatcher(rootPath.ToString()) { EnableRaisingEvents = true }; FileSystemEventHandler eventHandler = null; eventHandler = (s, e) => { XmlDocument devdoc = new XmlDocument(); devdoc.Load(devXMLPath); Log("Heel Development file has been updated!"); LoadXML(XDocument.Parse(devdoc.OuterXml), true); }; fsWatcher.Changed += eventHandler; fsWatcher.EnableRaisingEvents = true; } } catch (Exception e) { Log("Tried to load heel Development XML, but failed!"); Log(e.ToString()); } } }
static FileSystemWatcher CreateWatcher(string file, FileSystemEventHandler fseh, RenamedEventHandler reh) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = Path.GetFullPath(Path.GetDirectoryName(file)); watcher.Filter = Path.GetFileName(file); // This will enable the Modify flag for Linux/inotify watcher.NotifyFilter |= NotifyFilters.Size; watcher.Changed += fseh; watcher.Created += fseh; watcher.Deleted += fseh; watcher.Renamed += reh; watcher.EnableRaisingEvents = true; return(watcher); }
public static FileSystemEventHandler Throttle(this FileSystemEventHandler handler, TimeSpan throttle) { var throttling = false; return((s, e) => { if (throttling) { return; } handler(s, e); throttling = true; Task.Delay(throttle).ContinueWith(x => throttling = false); }); }
private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler handler) { if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) { syncObj.BeginInvoke(handler, new object[] { this, e }); } else { handler(this, e); } } }
public void CreateWatcher(string path, FileSystemEventHandler handler, string filter) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; if (filter != string.Empty) { watcher.Filter = filter; } watcher.Changed += handler; watcher.IncludeSubdirectories = true; //includeSubdirectories; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.EnableRaisingEvents = true; watcher.InternalBufferSize = 10240; }
/// <summary> /// Stops to watch a file. /// </summary> public void StopFileObserve(string filePath, FileSystemEventHandler eventHandler) { filePath = filePath.ToLowerInvariant(); if (_watchedResources.ContainsKey(filePath)) { var watchedFile = (WatchedFile)_watchedResources[filePath]; watchedFile.RemoveHandler(eventHandler); if (!watchedFile.HasHandles) { _watchedResources.Remove(filePath); } } }
/// <summary> /// Watches a folder for folder creation /// </summary> /// <param name="path">Which folder or fileshare to watch</param> /// <param name="actionOnFolderCreated">Action to perform when a change is detected. The action is invoked asynchronosly</param> public FolderChangeWatcher(string path, FileSystemEventHandler actionOnFolderCreated) { if (actionOnFolderCreated == null) { throw new ArgumentNullException("actionOnFolderCreated"); } _actionOnFolderCreated = actionOnFolderCreated; _watcher = new FileSystemWatcher(path); _watcher.Created += OnFolderCreated; _watcher.InternalBufferSize = 16384; //16KB buffer instead of 4KB (default). _watcher.IncludeSubdirectories = false; _watcher.EnableRaisingEvents = true; }
public static FileSystemWatcher Watch(string filePath, Action <string> fileChangeCompleted) { var watcher = new FileSystemWatcher { Path = Path.GetDirectoryName(filePath), Filter = $"{Path.GetFileNameWithoutExtension(filePath)}*{Path.GetExtension(filePath)}" }; FileSystemEventHandler handler = (sender, e) => FileChanged(sender, e, fileChangeCompleted); watcher.Created += handler; watcher.Changed += handler; return(watcher); }
/// <summary> /// 新建文件监视 /// </summary> /// <param name="seconds">超时检测秒数</param> /// <param name="onTimeout">超时处理</param> /// <param name="onTimeoutType">超时处理类型</param> /// <param name="log">日志处理</param> internal CreateFlieTimeoutWatcher(int seconds, object onTimeout, CreateFlieTimeoutType onTimeoutType, ILog log = null) { timeoutSeconds = Math.Max(seconds, 2); this.onTimeout = onTimeout; this.log = log ?? AutoCSer.Log.Pub.Log; switch (this.onTimeoutType = onTimeoutType) { case CreateFlieTimeoutType.HttpServerRegister: onCreatedHandle = onCreatedHttpServerRegister; break; default: onCreatedHandle = onCreated; break; } watchers = DictionaryCreator.CreateHashString <CreateFlieTimeoutCounter>(); Watchers.PushNotNull(this); WebView.OnTime.Set(Date.NowTime.OnTimeFlag.CreateFlieTimeoutWatcher); }
static void WatchDirectory(string directory, Action action) { var watcher = new FileSystemWatcher(); watcher.Path = directory; watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size; var handler = new FileSystemEventHandler((s, a) => action()); watcher.Changed += handler; watcher.Changed += handler; watcher.Created += handler; watcher.Deleted += handler; watcher.Renamed += new RenamedEventHandler((s, a) => action()); watcher.EnableRaisingEvents = true; }
public void Run() { /* Watch for changes in LastAccess and LastWrite times, and * the renaming of files or directories. */ Registry.Instance.LocalFileWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; Registry.Instance.LocalFileWatcher.IncludeSubdirectories = true; FileSystemEventHandler handler = new FileSystemEventHandler(OnCreated); Registry.Instance.LocalFileWatcher.Created -= handler; Registry.Instance.LocalFileWatcher.Created += handler; Registry.Instance.LocalFileWatcher.EnableRaisingEvents = true; }
// SetFolder private void SetDownloadFolder(string folder) { dfolderExists = false; tFolder.Text = folder; Config.Data.downloadFolder = folder; Config.Save(); dfolderExists = Directory.Exists(folder); dataGrid.Enabled = dfolderExists; bApply.Enabled = dfolderExists; lStatus.Enabled = dfolderExists; if (!dfolderExists) { lStatus.Text = "Status: Got no valid Download-Folder!"; } else { lStatus.Text = "Status: Ready"; FileSystemEventHandler onChanged = (object source, FileSystemEventArgs e) => { try { SortDownloadFolder(); } catch (Exception ex) { MessageBox.Show("Sorting Error: \n" + ex.ToString()); } }; RenamedEventHandler onRenamed = (object source, RenamedEventArgs e) => { try { SortDownloadFolder(); } catch (Exception ex) { MessageBox.Show("Sorting Error: \n" + ex.ToString()); } }; weightwatchers.Path = folder; weightwatchers.Changed += onChanged; weightwatchers.Created += onChanged; weightwatchers.Renamed += onRenamed; weightwatchers.EnableRaisingEvents = true; weightwatchers.IncludeSubdirectories = false; SortDownloadFolder(); } }
/// <summary> /// Change the Enabled property of the controls based on the current state. /// </summary> /* * private void UpdateControlEnabledStatus() * { * bool fileExists = false; * if (null != _fileName) fileExists = File.Exists(_fileName); * if (!_checkBoxUpdate.Checked) * { * // No updates desired * _textBoxTimeInterval.Enabled = false; * _radioButtonTimed.Enabled = false; * _radioButtonImmediate.Enabled = false; * } * else * { * if (!fileExists) * { * // If the file does not exist then immediate mode is not an option * _radioButtonTimed.Enabled = true; * _radioButtonImmediate.Enabled = false; * _radioButtonTimed.Checked = true; * _textBoxTimeInterval.Enabled = true; * } * else * { * _radioButtonTimed.Enabled = true; * _radioButtonImmediate.Enabled = true; * if (_radioButtonTimed.Checked) * { * _textBoxTimeInterval.Enabled = true; * } * else * { * _textBoxTimeInterval.Enabled = false; * } * } * } * } */ /// <summary> /// Hook up for the currently selected monitoring method. /// </summary> private void PrepareMonitoringMethod() { if (WatchMethod == MonitoringMethod.FileSystemWatcher) { // stop timer if running ClearTimer(); // If a file is set and the watcher has not been set up yet then create it if (null != _fileName && null == _watcher) { string path = Path.GetDirectoryName(_fileName); string baseName = Path.GetFileName(_fileName); // Use the FileSystemWatcher class to detect changes to the log file immediately // We must watch for Changed, Created, Deleted, and Renamed events to cover all cases _watcher = new System.IO.FileSystemWatcher(path, baseName); FileSystemEventHandler handler = new FileSystemEventHandler(watcher_Changed); _watcher.Changed += handler; _watcher.Created += handler; _watcher.Deleted += handler; _watcher.Renamed += watcher_Renamed; // Without setting EnableRaisingEvents nothing happens _watcher.EnableRaisingEvents = true; } } else { // On a timer so clear the watcher if previously set up ClearWatcher(); if (null != _timer) { // Timer is already running so just make sure the interval is correct if (_timer.Interval != this.UpdateInterval) { _timer.Interval = this.UpdateInterval; } } else { // Fire up a timer if the user entered a valid time interval if (0 != this.UpdateInterval) { _timer = new Timer(); _timer.Interval = this.UpdateInterval; _timer.Tick += timer_Tick; _timer.Start(); } } } }
/// <summary> /// Configure all new and existing <see cref="Chronicle"/> instances with options and libraries from an XML file. /// </summary> /// <param name="path">Path to the XML file.</param> /// <param name="watch">Watch for changes to the file and reconfigure when it changes.</param> /// <param name="watchBufferTime">Time in milliseconds to wait after a change to the file until reconfiguring.</param> public static void ConfigureFrom(string path, bool watch = true, int watchBufferTime = 1000) { if (_updateTimer != null) { #if NETFX _updateTimer.Stop(); #else _updateTimer.Change(Timeout.Infinite, Timeout.Infinite); #endif _updateTimer.Dispose(); _updateTimer = null; } if (watch) { #if NETFX _updateTimer = new Timer(watchBufferTime) { AutoReset = false }; _updateTimer.Elapsed += (a, b) => ConfigureFrom(path, true); #else var autoResetEvent = new AutoResetEvent(false); TimerCallback callBack = (s) => ConfigureFrom(path, true); _updateTimer = new Timer(callBack, null, watchBufferTime, Timeout.Infinite); #endif var directory = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(directory)) { directory = Directory.GetCurrentDirectory(); path = Path.Combine(directory, path); } var watcher = new FileSystemWatcher(directory); watcher.Filter = Path.GetFileName(path); FileSystemEventHandler resetUpdateTimer = (sender, args) => { #if NETFX _updateTimer.Stop(); _updateTimer.Start(); #else _updateTimer.Change(watchBufferTime, Timeout.Infinite); #endif }; watcher.Created += resetUpdateTimer; watcher.Changed += resetUpdateTimer; watcher.Deleted += resetUpdateTimer; watcher.EnableRaisingEvents = true; } ConfigureFrom(path, false); }
public static void StopFileWatch(string filter, string parentDirectory, FileSystemEventHandler callback) { var watcherInfo = _fileWatcherInfos.FirstOrDefault( info => info.FileWatcher.Filter == filter && info.FileWatcher.Path == parentDirectory); if (watcherInfo != null) { watcherInfo.TryRemoveSubscriber(callback); if (!watcherInfo.HasSubscribers()) { _fileWatcherInfos.Remove(watcherInfo); } } }
public FileWatcher(string filePath) { Changed = false; watcher = new FileSystemWatcher( Path.GetDirectoryName(filePath), Path.GetFileName(filePath) ); handler = new FileSystemEventHandler(watcher_Changed); watcher.Changed += handler; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.EnableRaisingEvents = true; }
public static FileSystemWatcher WatchFiles(string path, string filter, FileSystemEventHandler handler, NotifyFilters notify) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.IncludeSubdirectories = true; watcher.Filter = filter; watcher.Path = path; watcher.NotifyFilter = notify; watcher.Created += handler; watcher.Changed += handler; watcher.Deleted += handler; watcher.Renamed += (s, e) => { handler(s, new FileSystemEventArgs(e.ChangeType, e.FullPath, e.Name)); }; watcher.EnableRaisingEvents = true; return(watcher); }
public FileSystemWatcherWrapper(string path, FileSystemEventHandler created) : base() { Path = path; NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch csv files. Filter = "*.csv"; Created += created; // Begin watching. EnableRaisingEvents = true; }
public static FileSystemWatcher Watch(string path, FileSystemEventHandler handler) { var directory = Path.GetDirectoryName(path); var filename = Path.GetFileName(path); var fileSystemWatcher = new FileSystemWatcher { Path = directory, NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, Filter = filename }; fileSystemWatcher.Created += handler; fileSystemWatcher.Changed += handler; fileSystemWatcher.EnableRaisingEvents = true; return fileSystemWatcher; }
protected void OnDeleted(FileSystemEventArgs e) { FileSystemEventHandler onDeletedHandler = this.onDeletedHandler; if (onDeletedHandler != null) { if ((this.SynchronizingObject != null) && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.BeginInvoke(onDeletedHandler, new object[] { this, e }); } else { onDeletedHandler(this, e); } } }
public void Do_Not_Invoke_Exists_Files_Created_Event_For_Unsuitable_Files() { var callCount = 0; File.WriteAllText(this.FirstFilePath, "text"); using (var observer = new DirectoryObserver(this.PathToFiles, s => false)) { FileSystemEventHandler callBackHandler = (sender, args) => { callCount++; }; observer.Created += callBackHandler; observer.Start(); Thread.Sleep(1000); } callCount.Should().Be(0); }
public IDisposable WatchFileSystem(string path, string filter, FileSystemEventHandler handler) { var fileWatcher = new FileSystemWatcher(path, filter) { InternalBufferSize = 8192, }; fileWatcher.Created += handler; fileWatcher.Deleted += handler; fileWatcher.Changed += handler; fileWatcher.Renamed += (sender, args) => handler(sender, args); fileWatcher.EnableRaisingEvents = true; return(fileWatcher); }
void setupFileWatcher() { fileWatcher.Path = dir.FullName; fileWatcher.IncludeSubdirectories = false; fileWatcher.Filter = ""; fileWatcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName; createdHandler = fileWatcher_Created; deletedHandler = fileWatcher_Deleted; renamedHandler = fileWatcher_Renamed; fileWatcher.Created += createdHandler; fileWatcher.Deleted += deletedHandler; fileWatcher.Renamed += renamedHandler; fileWatcher.EnableRaisingEvents = true; }
/// <summary> /// Fallback polling thread for use when operating system does not support FileSystemWatcher /// </summary> /// <param name="folder">Folder to monitor</param> /// <param name="filename">File name to monitor</param> /// <param name="handler">Callback when file changes</param> private void PollingThread(string folder, string filename, FileSystemEventHandler handler) { string filePath = Path.Combine(folder, filename); DateTime lastWrite = GetLastWrite(filePath); while (true) { Thread.Sleep(5000); DateTime lastWriteNew = GetLastWrite(filePath); if (lastWriteNew != lastWrite) { lastWrite = lastWriteNew; handler(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, folder, filename)); } } }
/// <summary> /// Watches a folder for file changes matching filter /// </summary> /// <param name="path">Which folder or fileshare to watch</param> /// <param name="fileFilter">Which files to wathc for, ex *.txt</param> /// <param name="actionOnFileChanged">Action to perform when a change is detected. The action is invoked asynchronosly</param> /// <param name="filter">Which changes to act upon</param> public FileChangeWatcher(string path, string fileFilter, FileSystemEventHandler actionOnFileChanged, NotifyFilters filter) { if (actionOnFileChanged == null) { throw new ArgumentNullException("actionOnFileChanged"); } _actionOnFileChanged = actionOnFileChanged; _watcher = new FileSystemWatcher(path, fileFilter); _watcher.Changed += OnFileChanged; _watcher.InternalBufferSize = 16384; //16KB buffer instead of 4KB (default). _watcher.NotifyFilter = filter; _watcher.IncludeSubdirectories = false; _watcher.EnableRaisingEvents = true; }
/// <summary> /// Watches the Renamed WatcherChangeType and unblocks the returned AutoResetEvent when a /// Renamed event is thrown by the watcher. /// </summary> public static (AutoResetEvent EventOccured, FileSystemEventHandler Handler) WatchDeleted(FileSystemWatcher watcher, string[] expectedPaths = null) { AutoResetEvent eventOccurred = new AutoResetEvent(false); FileSystemEventHandler handler = (o, e) => { Assert.Equal(WatcherChangeTypes.Deleted, e.ChangeType); if (expectedPaths != null) { Assert.Contains(Path.GetFullPath(e.FullPath), expectedPaths); } eventOccurred.Set(); }; watcher.Deleted += handler; return(eventOccurred, handler); }
public async Task AttachFileObserver(IBundleDocument document, string fileName, Func<string, bool, Task> updateBundle) { _document = document; _bundleFileName = document.FileName; fileName = Path.GetFullPath(fileName); if (!File.Exists(fileName)) return; _watcher = new FileSystemWatcher { Path = Path.GetDirectoryName(fileName), Filter = Path.GetFileName(fileName), //_watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.LastWrite | NotifyFilters.Size; NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size }; using (await _rwLock.ReadLockAsync()) { if (WatchedFiles.ContainsKey(_bundleFileName) && WatchedFiles[_bundleFileName].Any(s => s.Item1.Equals(fileName, StringComparison.OrdinalIgnoreCase))) return; } _changeEvent = (_, __) => Changed(updateBundle); _watcher.Changed += _changeEvent; _watcher.Deleted += (_, __) => Deleted(fileName); if (_extensions.Any(e => fileName.EndsWith(e, StringComparison.OrdinalIgnoreCase))) _watcher.Renamed += (_, renamedEventArgument) => Renamed(renamedEventArgument, updateBundle); _watcher.EnableRaisingEvents = true; using (await _rwLock.WriteLockAsync()) { if (!WatchedFiles.ContainsKey(_bundleFileName)) WatchedFiles.Add(_bundleFileName, new HashSet<Tuple<string, FileSystemWatcher>>()); WatchedFiles[_bundleFileName].Add(new Tuple<string, FileSystemWatcher>(fileName, _watcher)); } }
public FileWatcher(string filepath, FileChangedHandler handler) : base(System.IO.Path.GetDirectoryName(filepath), System.IO.Path.GetFileName(filepath)) { FilePath = filepath; Handler = handler; NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; Changed += new FileSystemEventHandler(delegate(object sender, FileSystemEventArgs e) { Handler(FilePath); }); EnableRaisingEvents = true; }
public void InvokeHandlerFileSystemEventHandler() { var watcher = new FileSystemWatcher(_tempFolder); var wrapper = new BufferingFileSystemWatcher(watcher); var message = string.Empty; FileSystemEventHandler welcome = (_, s) => { message = s.FullPath; }; wrapper.InvokeHandler(welcome, null); wrapper.EnableRaisingEvents = false; wrapper.Dispose(); watcher.Dispose(); }
public FileWatch(string filePath) { Changed = false; var dir = Path.GetDirectoryName(filePath); if (string.IsNullOrEmpty(dir)) dir = "."; var name = Path.GetFileName(filePath); watcher = new FileSystemWatcher(dir, name) { NotifyFilter = NotifyFilters.LastWrite, EnableRaisingEvents = true }; handler = watcher_Changed; watcher.Changed += handler; }
private static void CreateWatcher( Settings settings, FileSystemEventHandler handler, RenamedEventHandler renamedHandler) { var watcher = new FileSystemWatcher(settings.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite, EnableRaisingEvents = true, Filter = "*.sql" }; watcher.Changed += handler; watcher.Created += handler; watcher.Deleted += handler; watcher.Renamed += renamedHandler; }
/// <summary> /// Constructor. /// </summary> public Watcher(string folder) { #if __MonoCS__ // http://stackoverflow.com/questions/16859372/why-doesnt-the-servicestack-razor-filesystemwatcher-work-on-mono-mac-os-x Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "enabled"); #endif Path = System.IO.Path.GetFullPath(folder); IncludeSubdirectories = true; Filter = "*"; InternalBufferSize = 4 * 1024 * 16; Error += new ErrorEventHandler(OnError); Created += new FileSystemEventHandler(OnCreated); Deleted += new FileSystemEventHandler(OnDeleted); Changed += new FileSystemEventHandler(OnChanged); Renamed += new RenamedEventHandler(OnRenamed); EnableRaisingEvents = true; EnableEvent = true; }
// Con /// <summary> /// Initializes a new instance of the i18n.FsCacheDependency class, given /// the specified directory and type of files to monitor. /// </summary> /// <param name="path"> /// The directory to monitor, in standard or Universal Naming Convention (UNC) notation. /// </param> /// <param name="includeSubdirectories"> /// Value indicating whether subdirectories within the specified path should be monitored. /// Defaults to true. /// </param> /// <param name="filespec"> /// The type of files to watch. For example, "*.txt" watches for changes to all text files. Defaults to "*.*". /// </param> /// <param name="changeTypes"> /// The type of changes to watch for. /// Defaults to a combination of LastWrite, FileName, and DirectoryName. /// </param> /// <param name="autoStart"> /// Indicates whether the monitoring it to begin immediately. /// If false, the caller must manipulate the EnableRaisingEvents property. /// Defaults to true. /// </param> public FsCacheDependency( string path, bool includeSubdirectories = true, string filespec = "*.*", NotifyFilters changeTypes = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite, bool autoStart = true) { // Init. m_fswatcher = new FileSystemWatcher(path, filespec); m_fswatcher.IncludeSubdirectories = includeSubdirectories; m_fswatcher.NotifyFilter = changeTypes; // Wire up event handlers. var handler = new FileSystemEventHandler(OnFsEvent); m_fswatcher.Changed += handler; m_fswatcher.Created += handler; m_fswatcher.Deleted += handler; m_fswatcher.Renamed += new RenamedEventHandler(OnFsEvent); // Conditionally start watching now. if (autoStart) { m_fswatcher.EnableRaisingEvents = true; } }
protected DocumentBase(string file, FileSystemEventHandler fileDeletedCallback) { _fileDeletedCallback = fileDeletedCallback; _file = file; var path = Path.GetDirectoryName(file); _localFileName = (Path.GetFileName(file) ?? "").ToLowerInvariant(); _watcher = new FileSystemWatcher { Path = path, Filter = _localFileName, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.LastAccess |NotifyFilters.DirectoryName }; _watcher.Changed += Reparse; _watcher.Deleted += ProxyDeletion; _watcher.Renamed += ProxyRename; _watcher.Created += Reparse; _watcher.EnableRaisingEvents = true; Reparse(); }
// based on documentation @ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx public static FileSystemWatcher GetWatcher(string directory, FileSystemEventHandler OnChanged) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = directory; /* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.wav"; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnChanged); // Begin watching. watcher.EnableRaisingEvents = true; return watcher; }
protected override void DoWork(CancellationToken token) { if (this.token.IsCancellationRequested) { this.DisableWatcher(); return; } try { this.token = token; bool watchSubdirectories = bool.Parse(this.configuration[WatchSubdirectoriesSetting]); this.fileSystemWatcher.Path = this.WatchPath; this.fileSystemWatcher.IncludeSubdirectories = watchSubdirectories; this.changeEventHandler = (source, args) => this.OnChanged(source, args); this.renamedEventHandler = this.OnRenamed; this.fileSystemWatcher.Created += changeEventHandler; this.fileSystemWatcher.Changed += changeEventHandler; this.fileSystemWatcher.Renamed += renamedEventHandler; this.CheckFolder().ContinueWith( (obj) => { this.fileSystemWatcher.EnableRaisingEvents = true; }, token); } catch (Exception ex) { this.logger.LogException(ex); throw; } }