//example:filter="*.txt" notifyFilters=NotifyFilters.LastWrite | NotifyFilters.FileName public void Initialize(string filter, NotifyFilters notifyFilters, string path) { FolderPath = path; _watcher.Path = path; _watcher.Filter = "*.txt"; _watcher.NotifyFilter = notifyFilters; }
public void FileSystemWatcher_File_NotifyFilter_Attributes(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { watcher.NotifyFilter = filter; var attributes = File.GetAttributes(file.Path); Action action = () => File.SetAttributes(file.Path, attributes | FileAttributes.ReadOnly); Action cleanup = () => File.SetAttributes(file.Path, attributes); WatcherChangeTypes expected = 0; if (filter == NotifyFilters.Attributes) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0)) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0)) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & NotifyFilters.Security) > 0)) expected |= WatcherChangeTypes.Changed; // Attribute change on OSX is a ChangeOwner operation which passes the Security NotifyFilter. ExpectEvent(watcher, expected, action, cleanup, file.Path); } }
public static VirtualPropertySet FromNotifyFilters(NotifyFilters filters) { VirtualPropertySet set = new VirtualPropertySet(); if ((filters & NotifyFilters.FileName) > 0) { set[0] = true; } if ((filters & NotifyFilters.Attributes) > 0) { set[6] = true; } if ((filters & NotifyFilters.Size) > 0) { set[3] = true; } if ((filters & NotifyFilters.LastWrite) > 0) { set[8] = true; } if ((filters & NotifyFilters.LastAccess) > 0) { set[9] = true; } if ((filters & NotifyFilters.CreationTime) > 0) { set[7] = true; } if ((filters & NotifyFilters.Security) > 0) { set[14] = true; } return set; }
public static IObservable<Unit> ObserveChanges(this PathSpec path, NotifyFilters filters) { var parent = path.Parent(); if (!parent.HasValue) return Observable.Never<Unit>(); return Observable.Create<Unit>(observer => { var watcher = new FileSystemWatcher(parent.Value.ToString()) { IncludeSubdirectories = false, Filter = path.Name, EnableRaisingEvents = true, NotifyFilter = filters }; var subscription = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(handler => watcher.Changed += handler, handler => watcher.Changed -= handler) .Select(_ => Unit.Default) .Subscribe(observer); return new AnonymousDisposable(() => { subscription.Dispose(); watcher.Dispose(); }); }); }
public FileSystemChangeNotification(string path) { this.FFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName; this.FPath = string.Empty; this.NotificationLock = new object(); this.Path = path; }
public static void TestNestedDirectoriesHelper( string testDirectory, WatcherChangeTypes change, Action<AutoResetEvent, TempDirectory> action, NotifyFilters changeFilers = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName) { using (var dir = new TempDirectory(testDirectory)) using (var watcher = new FileSystemWatcher()) { AutoResetEvent createdOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); // not "using" to avoid race conditions with FSW callbacks AutoResetEvent eventOccurred = WatchForEvents(watcher, change); watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = changeFilers; watcher.IncludeSubdirectories = true; watcher.EnableRaisingEvents = true; using (var firstDir = new TempDirectory(Path.Combine(dir.Path, "dir1"))) { ExpectEvent(createdOccurred, "dir1 created"); using (var nestedDir = new TempDirectory(Path.Combine(firstDir.Path, "nested"))) { ExpectEvent(createdOccurred, "nested created"); action(eventOccurred, nestedDir); } } } }
public WatcherEventArgs(FileSystemWatcher watcher, object arguments, ArgumentType argType) { this.Watcher = watcher; this.Arguments = arguments; this.ArgType = argType; this.Filter = NotifyFilters.Attributes; }
public void RememberSettingForNotifyFilter() { FileSystemWatcher tested = new FileSystemWatcher(); NotifyFilters filters = NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.Security | NotifyFilters.LastAccess; tested.NotifyFilter = filters; Assert.AreEqual(filters, tested.NotifyFilter); }
public WatcherExEventArgs(FileSystemWatcherEx watcher, object arguments, ArgumentType argType) { Watcher = watcher; Arguments = arguments; ArgType = argType; Filter = NotifyFilters.Attributes; }
/// <summary> /// </summary> private void MonitoringInput_CheckedChanged(object sender, EventArgs e) { string monitoredFolder = FolderInput.Text; bool folderExists = Directory.Exists(monitoredFolder); if (folderExists) { _watcher.Path = monitoredFolder; _watcher.Filter = FileFilterInput.Text; _watcher.IncludeSubdirectories = SubfoldersInput.Checked; NotifyFilters notificationFilters = new NotifyFilters(); if (AttributesInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.Attributes; } if (CreationTimeInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.CreationTime; } if (DirectoryNameInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.DirectoryName; } if (FileNameInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.FileName; } if (LastAccessInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.LastAccess; } if (LastWriteInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.LastWrite; } if (SecurityInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.Security; } if (SizeInput.Checked) { notificationFilters = notificationFilters | NotifyFilters.Size; } _watcher.NotifyFilter = notificationFilters; _watcher.EnableRaisingEvents = MonitoringInput.Checked; } else if (MonitoringInput.Checked) { MessageBox.Show(this, "Esta carpeta no existe.", "Directorio Invalido", MessageBoxButtons.OK, MessageBoxIcon.Error); MonitoringInput.Checked = false; } FolderInput.Enabled = FileFilterInput.Enabled = NotificationsGroup.Enabled = !MonitoringInput.Checked; }
// Constructors. public FileSystemWatcher() { this.path = String.Empty; this.filter = "*.*"; this.internalBufferSize = 8192; this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; }
public FSWParams(string path, string filter = "*.*") { this.path = path; this.filter = filter; notifiers = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size; includeSubfolders = true; }
public AggregateFileSystemWatcher(IFileSystem fileSystem, UPath path) : base(fileSystem, path) { _children = new List <IFileSystemWatcher>(); _internalBufferSize = 0; _notifyFilter = NotifyFilters.Default; _enableRaisingEvents = false; _includeSubdirectories = false; _filter = "*.*"; }
/// <summary> /// Initializes a new instance of the <b>FileSystemMonitor</b> 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="filter">The type of files to watch. For example, "*.txt" watches for changes to all text files.</param> public FileSystemMonitor(string path, string filter) { notifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.DirectoryName; #if !NDOC notificationMonitor = new FileNotificationMonitor(this); #endif this.Path = path; this.Filter = filter; }
public FileSystemWatcher() { this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; this.enableRaisingEvents = false; this.filter = "*.*"; this.includeSubdirectories = false; this.internalBufferSize = 8192; this.path = ""; InitWatcher(); }
public FakeSystemChangeEventArgs(WatcherChangeTypes changeType, NotifyFilters filters, [NotNull] IPathFormatter pathFormatter, [CanBeNull] IPathFormatter previousPathInRenameFormatter) { Guard.NotNull(pathFormatter, nameof(pathFormatter)); ChangeType = changeType; Filters = filters; PathFormatter = pathFormatter; PreviousPathInRenameFormatter = previousPathInRenameFormatter; }
/// <summary> /// 文件监视器构造函数 /// </summary> /// <param name="path">要监控的目录路径</param> /// <param name="filter">要过滤的文件,可以是具体的文件名或搜索条件如:a.txt或*.txt</param> /// <param name="notifyFilters">NotifyFilters 枚举,需多个时用 | 分开</param> /// <param name="OnChangedCallbackMethod">当监测的文件发生改变时触发的回调函数,接收一个FileSystemEventArgs类型的参数</param> public UDFFileSystemWatcher(string path, string filter, NotifyFilters notifyFilters, TAction <FileSystemEventArgs> OnChangedCallbackMethod) { _fsWatcher = new FileSystemWatcher(path, filter); _fsWatcher.NotifyFilter = notifyFilters; _fsWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed); _onChangedCallbackMethod = OnChangedCallbackMethod; _executeChanged = new InvokeMethod(FileSystemOnChangedCallbackMethod); }
public FileSystemWatcher () { this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; this.enableRaisingEvents = false; this.filter = "*.*"; this.includeSubdirectories = false; this.internalBufferSize = 8192; this.path = ""; InitWatcher (); }
public FolderListener(object caller, string folderName, string filter = "*.*", bool monitorSubFolders = false, WatcherChangeTypes monitorChangeTypes = WatcherChangeTypes.All, NotifyFilters notificationFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size) : base(caller) { _folderWatcher = new FileSystemWatcher(folderName, filter) { IncludeSubdirectories = monitorSubFolders }; MonitorChangeTypes = monitorChangeTypes; NotificationFilter = notificationFilter; }
/// <summary>Initializes a new instance of the <see cref="T:System.IO.FileSystemWatcher" /> class.</summary> public FileSystemWatcher() { notifyFilter = (NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite); enableRaisingEvents = false; filter = "*.*"; includeSubdirectories = false; internalBufferSize = 8192; path = string.Empty; InitWatcher(); }
private IFileSystemWatcher CreateFileSystemWatcher(NotifyFilters notifyFilter) { var watcher = _fileSystem.CreateFileSystemWatcher(_directory, _filter); watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; watcher.InternalBufferSize = 65536; watcher.NotifyFilter = notifyFilter; return(watcher); }
public WatcherEventArgs(FileSystemWatcher watcher, object arguments, ArgumentType argType, NotifyFilters filter) { this.Watcher = watcher; this.Arguments = arguments; this.ArgType = argType; this.Filter = filter; }
/// <summary> /// Initializes a new instance of the <see cref="WatcherEventArgs"/> class. /// </summary> /// <param name="watcher">The watcher.</param> /// <param name="arguments">The arguments.</param> /// <param name="argumentType">Type of the argument.</param> /// <param name="filter">The filter.</param> protected BaseEventArgs(TWatcher watcher, object arguments, FileWatcherArgumentTypes argumentType, NotifyFilters filter) { Watcher = watcher; Arguments = arguments; ArgumentType = argumentType; Filter = filter; }
public WatcherExEventArgs(FileSystemWatcherEx watcher, object arguments, ArgumentType argType, NotifyFilters filter) { Watcher = watcher; Arguments = arguments; ArgType = argType; Filter = filter; }
private NotifyFilters ParseFileWatcherNotifyFilter(string fileWatcherNotifyFilter) { FileSystemWatcher fileWatcher = new FileSystemWatcher(); fileWatcher.NotifyFilter = (System.IO.NotifyFilters)FileWatcher.NotifyFilters.None; string[] notifyFilters = fileWatcherNotifyFilter.Split(notifyFiltersDelimiter); foreach (var notifyFilter in notifyFilters) { Logging.Log(LogLevelEnum.Debug, string.Format("Adding NotifyFilter: {0}", notifyFilter)); switch (notifyFilter) { case "FN": SetNotifyFilter(NotifyFilters.FileName, fileWatcher); break; case "DN": SetNotifyFilter(NotifyFilters.DirectoryName, fileWatcher); break; case "A": SetNotifyFilter(NotifyFilters.Attributes, fileWatcher); break; case "SZ": SetNotifyFilter(NotifyFilters.Size, fileWatcher); break; case "LW": SetNotifyFilter(NotifyFilters.LastWrite, fileWatcher); break; case "LA": SetNotifyFilter(NotifyFilters.LastAccess, fileWatcher); break; case "CT": SetNotifyFilter(NotifyFilters.CreationTime, fileWatcher); break; case "S": SetNotifyFilter(NotifyFilters.Security, fileWatcher); break; } } NotifyFilters returnFilter = fileWatcher.NotifyFilter; Logging.Log(LogLevelEnum.Debug, string.Format("Returning returnFilter: {0}", returnFilter)); fileWatcher.Dispose(); // MUST call this to release the FileWatcher created during filter parsing! Memory leak WILL be created otherwise! return(returnFilter); }
private NotifyFilters GetUnionForFilters() { NotifyFilters filters = 0; foreach (WatcherNotifyTestLine testLine in testLines) { filters |= testLine.Filters; } return(filters); }
public async Task IncrementCount(Watcher watcher, NotifyFilters notifyFilter) { string countPropertyName = DirWatcherTransferApp.SymbolicLinkNotifyFilterCountMap[notifyFilter]; PropertyInfo propertyInfo = watcher.GetType().GetProperty(countPropertyName); int currentCount = ((int)propertyInfo.GetValue(watcher)); propertyInfo.SetValue(watcher, currentCount++); await this.UpdateAsync(watcher); }
private void SetNotifyFilter(NotifyFilters filter, FileSystemWatcher fileWatcher) { if ((FileWatcher.NotifyFilters)fileWatcher.NotifyFilter == FileWatcher.NotifyFilters.None) { fileWatcher.NotifyFilter = filter; } else { fileWatcher.NotifyFilter |= filter; } }
private void createStartupTask() { TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "Monitors " + txtFolder.Text + " for files of format \"" + txtFilter.Text + "\" with changes in"; Array notifyFilters = Enum.GetValues(typeof(NotifyFilters)); foreach (object s in notifyFilters) { NotifyFilters f = (NotifyFilters)Enum.Parse(typeof(NotifyFilters), s.ToString()); if ((f & watcher.NotifyFilter) == f) { td.RegistrationInfo.Description += ' ' + f.ToString() + ','; } } if (td.RegistrationInfo.Description.IndexOf(',') != td.RegistrationInfo.Description.LastIndexOf(',')) { string lastItem = td.RegistrationInfo.Description.Substring(td.RegistrationInfo.Description.LastIndexOf(' ')); lastItem.Replace(" ", " and "); td.RegistrationInfo.Description = td.RegistrationInfo.Description.Remove(td.RegistrationInfo.Description.LastIndexOf(' ')); td.RegistrationInfo.Description += lastItem; } int idx = td.RegistrationInfo.Description.LastIndexOf(','); if (idx > 0) { td.RegistrationInfo.Description = td.RegistrationInfo.Description.Remove(idx); td.RegistrationInfo.Description += '.'; } else { td.RegistrationInfo.Description += " [no attributes selected]."; } td.Triggers.Add(new LogonTrigger()); string filePath = Application.ExecutablePath; string arguments = "\"" + txtFolder.Text + (txtFilter.Text.Contains("*") ? "" : '\\' + txtFilter.Text) + "\" " + (int)watcher.NotifyFilter + (IncludeSubdirs.Checked ? " /r" : " /nr"); td.Actions.Add(filePath, arguments); setTaskName(); td.Settings.ExecutionTimeLimit = new TimeSpan(0); td.Settings.StopIfGoingOnBatteries = false; td.Settings.DisallowStartIfOnBatteries = false; ts.RootFolder.RegisterTaskDefinition(taskName, td); }
private void Init() { defaultNotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; defaultFilter = Wxg.Utils.Xmler.GetAppSettingValue("filter", "*.*"); // Add event handlers. this.Changed += new FileSystemEventHandler(OnChanged); this.Created += new FileSystemEventHandler(OnChanged); this.Deleted += new FileSystemEventHandler(OnChanged); this.Renamed += new RenamedEventHandler(OnRenamed); }
public static IDisposable SubscribeToFolderChanges <T>( string directoryPath, string fileWildcardSpecification, bool includeSubdirectories, NotifyFilters notifyFilters, IObserver <T> observer, Func <FileSystemEventArgs, T> createdSelector = null, Func <FileSystemEventArgs, T> changedSelector = null, Func <FileSystemEventArgs, T> deletedSelector = null, Func <RenamedEventArgs, T> renamedSelector = null) { FileSystemWatcher disposable = null; try { var fsw = disposable = new FileSystemWatcher(directoryPath, fileWildcardSpecification) { NotifyFilter = notifyFilters, IncludeSubdirectories = includeSubdirectories, }; if (createdSelector != null) { fsw.Created += (_, args) => observer.OnNext(createdSelector(args)); } if (changedSelector != null) { fsw.Changed += (_, args) => observer.OnNext(changedSelector(args)); } if (deletedSelector != null) { fsw.Deleted += (_, args) => observer.OnNext(deletedSelector(args)); } if (renamedSelector != null) { fsw.Renamed += (_, args) => observer.OnNext(renamedSelector(args)); } fsw.Error += (_, args) => observer.OnError(args.GetException()); fsw.EnableRaisingEvents = true; disposable = null; return(new DelegatingDisposable(() => { fsw.Dispose(); observer.OnCompleted(); })); } finally { disposable?.Dispose(); } }
/// <summary> /// Creates an instance of <see cref="FileSystemWatcher"/> with the specified path. /// </summary> /// <param name="path">Path for the watcher to watch</param> /// <param name="delegates">Delegates for <see cref="FileSystemWatcher"/> events. (see <see cref="WatcherDelegates"/>)</param> /// <returns>The created watcher</returns> public static FileSystemWatcher CreateWatcher(string path, WatcherDelegates delegates) { NotifyFilters all = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Security; return(CreateWatcher(path, all, delegates)); }
public WatcherNotifyTestLine Parse() { Reset(); SkipToMarkerOffset(); string expectation = line.Substring(0, position).Trim(); ConsumeSeparators(); NotifyFilters filters = ParseNotifyFilterList(); return(new WatcherNotifyTestLine(expectation, filters)); }
/// <summary> /// Initializes a new instance of the FileWatcher class. /// </summary> public FileWatcher(string watchedFolder, string filter, NotifyFilters notifyFilter, TimeSpan eventTriggerInterval, TimeSpan delayNotificationBy) { _watchedFolder = watchedFolder; _filter = filter; _notifyFilter = notifyFilter; _eventTriggerInterval = eventTriggerInterval; _delayNotificationBy = delayNotificationBy; ConfigureWatcher(); }
public FileSystemWatcherHelper(string path, string filter, NotifyFilters notifyFilter, bool incluedSubDirectory = true) { if (string.IsNullOrEmpty(path)) { path = AppDomain.CurrentDomain.BaseDirectory; } fileSystemWatcher.Path = path; fileSystemWatcher.Filter = filter; fileSystemWatcher.NotifyFilter = notifyFilter; fileSystemWatcher.IncludeSubdirectories = incluedSubDirectory; InitEvents(); }
public Watcher(Life.Trigger trigger, string filename, NotifyFilters notify = NotifyFilters.LastWrite) : this(trigger) { _watcher = new FileSystemWatcher { Path = System.IO.Path.GetDirectoryName(filename), NotifyFilter = notify, EnableRaisingEvents = true, Filter = System.IO.Path.GetFileName(filename) }; _watcher.Changed += (sender, args) => OnTriggered(filename); }
public Watcher(Life.Trigger trigger, string path, string filter, NotifyFilters notify = NotifyFilters.LastWrite) : this(trigger) { _watcher = new FileSystemWatcher { Path = path, NotifyFilter = notify, EnableRaisingEvents = true, Filter = filter }; _watcher.Changed += (sender, args) => OnTriggered(System.IO.Path.Combine(path, filter)); }
public DirectoryWatcher(string watchDirectory, Action<object, FileSystemEventArgs> handler, NotifyFilters notifyFilters) { if (Directory.Exists(watchDirectory)){ watcher = new FileSystemWatcher(watchDirectory); watcher.NotifyFilter = notifyFilters; watcher.Created += new FileSystemEventHandler(handler); watcher.Changed += new FileSystemEventHandler(handler); } else { throw new Exception("Directory does not exist!"); } }
/// <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; }
public FileQueueWatcher ( string path, string filter, TextWriter logWriter ) { m_path = path; m_logWriter = logWriter; m_filter = filter; m_imageResizeProcessManager = new NuxleusImageResizeProcessManager(path, logWriter); m_notifyFilters = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName; this.Path = m_path; this.NotifyFilter = m_notifyFilters; this.Filter = m_filter; }
public FileSystemWatcher(String path) { if(path == null) { throw new ArgumentNullException("path"); } else if(path.Length == 0) { throw new ArgumentException(S._("IO_InvalidPathname")); } this.filter = "*.*"; this.internalBufferSize = 8192; this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; }
public Watcher(string path, string filter, TextWriter logWriter) { _path = path; _logWriter = logWriter; _filter = filter; _notifyFilters = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; _darcsProc = new DarcsProcess(path, logWriter); this.Path = _path; this.NotifyFilter = _notifyFilters; this.Filter = _filter; }
public void FileSystemWatcher_File_NotifyFilter_CreationTime(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { watcher.NotifyFilter = filter; Action action = () => File.SetCreationTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); WatcherChangeTypes expected = 0; if (filter == NotifyFilters.CreationTime) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0)) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0)) expected |= WatcherChangeTypes.Changed; ExpectEvent(watcher, expected, action, expectedPath: file.Path); } }
// 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; } }
public Guid RegisterListener(IComparable queueName, string path, string filter, NotifyFilters notifyFilter, bool includeSubdirectories) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); try { fileSystemWatcher.Path = path; } catch (ArgumentException) { Console.WriteLine("Path \"{0}\" not found. Please see documentation for setup steps.", path); return Guid.Empty; } fileSystemWatcher.Filter = filter; fileSystemWatcher.NotifyFilter = notifyFilter; fileSystemWatcher.IncludeSubdirectories = includeSubdirectories; fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Handler); fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_Handler); fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_Handler); fileSystemWatcher.Error += new ErrorEventHandler(FileSystemWatcher_Error); FileWatcherSubscription subscription = new FileWatcherSubscription(fileSystemWatcher, WorkflowEnvironment.WorkflowInstanceId, queueName); Guid subscriptionId = Guid.NewGuid(); lock (this.subscriptions) { this.subscriptions.Add(subscriptionId.ToString(), subscription); } // Turn the file system watcher on fileSystemWatcher.EnableRaisingEvents = true; Console.WriteLine("FileWatcherService subscription '" + subscriptionId.ToString() + "' created"); return subscriptionId; }
public void FileSystemWatcher_Directory_NotifyFilter_DirectoryName(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(dir.Path))) { string sourcePath = dir.Path; string targetPath = Path.Combine(testDirectory.Path, "targetDir"); watcher.NotifyFilter = filter; Action action = () => Directory.Move(sourcePath, targetPath); Action cleanup = () => Directory.Move(targetPath, sourcePath); WatcherChangeTypes expected = 0; if (filter == NotifyFilters.DirectoryName) expected |= WatcherChangeTypes.Renamed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && (filter == NotifyFilters.FileName)) expected |= WatcherChangeTypes.Renamed; ExpectEvent(watcher, expected, action, cleanup, targetPath); } }
public MultiFileWatcher(NotifyFilters notifyFilters) { NotifyFilters = notifyFilters; }
/// <summary> /// Initialize the file and notification filters associated with this watcher. /// </summary> /// <param name="genericFilter"></param> /// <param name="notificationFilters"></param> private void InitializeFilters(string genericFilter, NotifyFilters notificationFilters) { _watcher.Filter = (!String.IsNullOrEmpty(genericFilter)) ? genericFilter : _defaultFilter; _watcher.NotifyFilter = notificationFilters; }
private void Notifications() { this.fsw.Path = this.txtFolder.Text; this.fsw.Filter = this.cmbWatchExtension.Text; this.fsw.IncludeSubdirectories = this.miMonitorSubfolders.Checked; // Notification filters NotifyFilters notificationFilters = new NotifyFilters(); if (this.miMonitorAttributes.Checked) notificationFilters = notificationFilters | NotifyFilters.Attributes; if (this.miMonitorCreation.Checked) notificationFilters = notificationFilters | NotifyFilters.CreationTime; if (this.miMonitorDirectory.Checked) notificationFilters = notificationFilters | NotifyFilters.DirectoryName; if (this.miMonitorFilename.Checked) notificationFilters = notificationFilters | NotifyFilters.FileName; if (this.miMonitorAccess.Checked) notificationFilters = notificationFilters | NotifyFilters.LastAccess; if (this.miMonitorWrite.Checked) notificationFilters = notificationFilters | NotifyFilters.LastWrite; if (this.miMonitorSecurity.Checked) notificationFilters = notificationFilters | NotifyFilters.Security; if (this.miMonitorSize.Checked) notificationFilters = notificationFilters | NotifyFilters.Size; this.fsw.NotifyFilter = notificationFilters; }
public void FileSystemWatcher_Directory_NotifyFilter_Security(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(dir.Path))) { watcher.NotifyFilter = filter; Action action = () => { // ACL support is not yet available, so pinvoke directly. uint result = SetSecurityInfoByHandle(dir.Path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, // Only setting the DACL owner: IntPtr.Zero, group: IntPtr.Zero, dacl: IntPtr.Zero, // full access to everyone sacl: IntPtr.Zero); Assert.Equal(ERROR_SUCCESS, result); }; Action cleanup = () => { // Recreate the Directory. Directory.Delete(dir.Path); Directory.CreateDirectory(dir.Path); }; WatcherChangeTypes expected = 0; if (filter == NotifyFilters.Security) expected |= WatcherChangeTypes.Changed; ExpectEvent(watcher, expected, action, cleanup, dir.Path); } }
public void FileSystemWatcher_File_NotifyFilter_Security(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { watcher.NotifyFilter = filter; Action action = () => { // ACL support is not yet available, so pinvoke directly. uint result = SetSecurityInfoByHandle(file.Path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, // Only setting the DACL owner: IntPtr.Zero, group: IntPtr.Zero, dacl: IntPtr.Zero, // full access to everyone sacl: IntPtr.Zero); Assert.Equal(ERROR_SUCCESS, result); }; Action cleanup = () => { // Recreate the file. File.Delete(file.Path); File.AppendAllText(file.Path, "text"); }; WatcherChangeTypes expected = 0; if (filter == NotifyFilters.Security) expected |= WatcherChangeTypes.Changed; else if (PlatformDetection.IsWindows7 && filter == NotifyFilters.Attributes) // win7 FSW Security change passes the Attribute filter expected |= WatcherChangeTypes.Changed; ExpectEvent(watcher, expected, action, expectedPath: file.Path); } }
public void FileSystemWatcher_File_NotifyFilter_Size(NotifyFilters filter) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { watcher.NotifyFilter = filter; Action action = () => File.AppendAllText(file.Path, "longText!"); Action cleanup = () => File.AppendAllText(file.Path, "short"); WatcherChangeTypes expected = 0; if (filter == NotifyFilters.Size || filter == NotifyFilters.LastWrite) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForModify) > 0)) expected |= WatcherChangeTypes.Changed; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0)) expected |= WatcherChangeTypes.Changed; else if (PlatformDetection.IsWindows7 && filter == NotifyFilters.Attributes) // win7 FSW Size change passes the Attribute filter expected |= WatcherChangeTypes.Changed; ExpectEvent(watcher, expected, action, expectedPath: file.Path); } }
public FileSystemWatcher (string path, string filter) { if (path == null) throw new ArgumentNullException ("path"); if (filter == null) throw new ArgumentNullException ("filter"); if (path == String.Empty) throw new ArgumentException ("Empty path", "path"); if (!Directory.Exists (path)) throw new ArgumentException ("Directory does not exists", "path"); this.enableRaisingEvents = false; this.filter = filter; this.includeSubdirectories = false; this.internalBufferSize = 8192; this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; this.path = path; this.synchronizingObject = null; InitWatcher (); }
/// <summary> /// Maps the FileSystemWatcher's NotifyFilters enumeration to the /// corresponding Interop.libc.NotifyEvents values. /// </summary> /// <param name="filters">The filters provided the by user.</param> /// <returns>The corresponding NotifyEvents values to use with inotify.</returns> private static Interop.libc.NotifyEvents TranslateFilters(NotifyFilters filters) { Interop.libc.NotifyEvents result = 0; // We always include a few special inotify watch values that configure // the watch's behavior. result |= Interop.libc.NotifyEvents.IN_ONLYDIR | // we only allow watches on directories Interop.libc.NotifyEvents.IN_EXCL_UNLINK; // we want to stop monitoring unlinked files // For the Created and Deleted events, we need to always // register for the created/deleted inotify events, regardless // of the supplied filters values. We explicitly don't include IN_DELETE_SELF. // The Windows implementation doesn't include notifications for the root directory, // and having this for subdirectories results in duplicate notifications, one from // the parent and one from self. result |= Interop.libc.NotifyEvents.IN_CREATE | Interop.libc.NotifyEvents.IN_DELETE; // For the Changed event, which inotify events we subscribe to // are based on the NotifyFilters supplied. const NotifyFilters filtersForAccess = NotifyFilters.LastAccess; const NotifyFilters filtersForModify = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; const NotifyFilters filtersForAttrib = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; if ((filters & filtersForAccess) != 0) { result |= Interop.libc.NotifyEvents.IN_ACCESS; } if ((filters & filtersForModify) != 0) { result |= Interop.libc.NotifyEvents.IN_MODIFY; } if ((filters & filtersForAttrib) != 0) { result |= Interop.libc.NotifyEvents.IN_ATTRIB; } // For the Rename event, we'll register for the corresponding move inotify events if the // caller's NotifyFilters asks for notications related to names. const NotifyFilters filtersForMoved = NotifyFilters.FileName | NotifyFilters.DirectoryName; if ((filters & filtersForMoved) != 0) { result |= Interop.libc.NotifyEvents.IN_MOVED_FROM | Interop.libc.NotifyEvents.IN_MOVED_TO; } return result; }
public void startWatching() { if (!isRunning) { if (!Directory.Exists(Properties.Settings.Default.folder)) { System.Windows.MessageBox.Show("Folder " + Properties.Settings.Default.folder + " does not exist"); return; } isRunning = true; mainWindow.startButton.Content = "Stop watching"; mainWindow.startButton.Background = System.Windows.Media.Brushes.Red; mainWindow.radioButtonUseLocalNotifications.IsEnabled = false; mainWindow.radioButtonUseSnpNotifications.IsEnabled = false; mainWindow.targetIP.IsEnabled = false; mainWindow.targetPort.IsEnabled = false; mainWindow.textBoxPath.IsEnabled = false; mainWindow.checkBoxIncludeSubdirectories.IsEnabled = false; mainWindow.textBoxFilter.IsEnabled = false; mainWindow.checkBoxAttributes.IsEnabled = false; mainWindow.checkBoxChanged.IsEnabled = false; mainWindow.checkBoxCreated.IsEnabled = false; mainWindow.checkBoxDeleted.IsEnabled = false; mainWindow.checkBoxLastAccess.IsEnabled = false; mainWindow.checkBoxLastWrite.IsEnabled = false; mainWindow.checkBoxRenamed.IsEnabled = false; mainWindow.checkBoxSize.IsEnabled = false; mainWindow.checkBoxDirectoryName.IsEnabled = false; mainWindow.checkBoxFilename.IsEnabled = false; mainWindow.chooseFolder.IsEnabled = false; RegisterWithSnarl(); watcher.Path = Properties.Settings.Default.folder; NotifyFilters myFilter = new NotifyFilters(); NotifyFilters emptyFilter = new NotifyFilters(); if (Properties.Settings.Default.fAttributes) { myFilter = NotifyFilters.Attributes; } if (Properties.Settings.Default.fDirname) { myFilter = myFilter | NotifyFilters.DirectoryName; } if (Properties.Settings.Default.fFilename) { myFilter = myFilter | NotifyFilters.FileName; } if (Properties.Settings.Default.fLastAccess) { myFilter = myFilter | NotifyFilters.LastAccess; } if (Properties.Settings.Default.fLastWrite) { myFilter = myFilter | NotifyFilters.LastWrite; } if (Properties.Settings.Default.fSize) { myFilter = myFilter | NotifyFilters.Size; } if (myFilter != emptyFilter) { watcher.NotifyFilter = myFilter; } else { watcher.NotifyFilter = NotifyFilters.FileName; } watcher.Filter = Properties.Settings.Default.filter; watcher.IncludeSubdirectories = Properties.Settings.Default.includeSubdirs; // Add event handlers. if (Properties.Settings.Default.fChanged) { watcher.Changed += new FileSystemEventHandler(OnChanged); } if (Properties.Settings.Default.fCreated) { watcher.Created += new FileSystemEventHandler(OnChanged); } if (Properties.Settings.Default.fDeleted) { watcher.Deleted += new FileSystemEventHandler(OnChanged); } if (Properties.Settings.Default.fRenamed) { watcher.Renamed += new RenamedEventHandler(OnRenamed); } watcher.EnableRaisingEvents = true; } else { isRunning = false; if (Properties.Settings.Default.snarlLocal) { snarl.Unregister(); } else { snarlNetwork.unregister(Properties.Settings.Default.snpIp, Properties.Settings.Default.snpPort, "FileSystemSnarl"); } watcher.EnableRaisingEvents = false; mainWindow.startButton.Content = "Start forwarding"; mainWindow.startButton.Background = System.Windows.Media.Brushes.GreenYellow; mainWindow.radioButtonUseLocalNotifications.IsEnabled = true; mainWindow.radioButtonUseSnpNotifications.IsEnabled = true; mainWindow.targetIP.IsEnabled = true; mainWindow.targetPort.IsEnabled = true; mainWindow.textBoxPath.IsEnabled = true; mainWindow.checkBoxIncludeSubdirectories.IsEnabled = true; mainWindow.textBoxFilter.IsEnabled = true; mainWindow.checkBoxAttributes.IsEnabled = true; mainWindow.checkBoxChanged.IsEnabled = true; mainWindow.checkBoxCreated.IsEnabled = true; mainWindow.checkBoxDeleted.IsEnabled = true; mainWindow.checkBoxLastAccess.IsEnabled = true; mainWindow.checkBoxLastWrite.IsEnabled = true; mainWindow.checkBoxRenamed.IsEnabled = true; mainWindow.checkBoxSize.IsEnabled = true; mainWindow.checkBoxDirectoryName.IsEnabled = true; mainWindow.checkBoxFilename.IsEnabled = true; mainWindow.chooseFolder.IsEnabled = true; } }
public NotificationWaitHandle(string pathName, bool watchSubtree, NotifyFilters filter) { this.FPath = pathName; this.FWatchSubtree = watchSubtree; this.FFilter = filter; }
private static extern SafeNotificationHandle FindFirstChangeNotification([MarshalAs(UnmanagedType.LPTStr)] string lpPathName, [MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, NotifyFilters dwNotifyFilter);
/// <summary> /// Initializes a new instance of the <see cref="FileCacheDependency"/> class. /// </summary> /// <param name="fileName">The file name with the path.</param> /// <param name="filters">The file changed notify type.</param> public FileCacheDependency(string fileName, NotifyFilters filters) { this.fileName = fileName; this.filters = filters; this.WatchFile(); }
/// <summary> /// Initializes a new instance of the FileWatcher class. /// </summary> public FileWatcher (string watchedFolder, string filter, NotifyFilters notifyFilter, TimeSpan eventTriggerInterval, TimeSpan delayNotificationBy) { _watchedFolder = watchedFolder; _filter = filter; _notifyFilter = notifyFilter; _eventTriggerInterval = eventTriggerInterval; _delayNotificationBy = delayNotificationBy; ConfigureWatcher (); }