public FileWatcher(string directory, string filter) { _dispatcher = Dispatcher.CurrentDispatcher; _watcher = new FileSystemWatcher(); _watcher.BeginInit(); _watcher.Path = directory; _watcher.Filter = filter; _watcher.IncludeSubdirectories = false; _watcher.InternalBufferSize = InitialBufferSize; _watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Attributes | NotifyFilters.Security | NotifyFilters.Size; // note: all events are on threadpool threads! _watcher.Created += onCreated; _watcher.Deleted += onDeleted; _watcher.Changed += onChanged; _watcher.Renamed += onRenamed; _watcher.Error += onError; _watcher.EndInit(); _watcher.EnableRaisingEvents = true; }
private SNTemplateManager(string snTmplRuleFilePath) { rulesfileWatcher = new FileSystemWatcher(); rulesfileWatcher.BeginInit(); rulesfileWatcher.EnableRaisingEvents = true; rulesfileWatcher.Filter = "*.rules"; rulesfileWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite; rulesfileWatcher.Path = snTmplRuleFilePath; rulesfileWatcher.Changed += new FileSystemEventHandler(ruleFileWatcher_Changed); rulesfileWatcher.EndInit(); }
private DeserializedRuleSetsManager() { snTmplRuleFilePath = ConfigurationManager.AppSettings["RulePath"].ToString(); irm = RuleSetManagerFactory.CreateFileRuleSetManager(); rulesfileWatcher = new FileSystemWatcher(); rulesfileWatcher.BeginInit(); rulesfileWatcher.EnableRaisingEvents = true; rulesfileWatcher.Filter = "*.rules"; rulesfileWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite; rulesfileWatcher.Path = snTmplRuleFilePath; rulesfileWatcher.Changed += new FileSystemEventHandler(ruleFileWatcher_Changed); rulesfileWatcher.EndInit(); }
protected override void OnStart(string[] args) { Thread.Sleep(15000); log = new EventLog(); log.Source = "S1 Payment Operator Service"; setting = new Setting(); files = new ArrayList(); fileWatcher = new FileSystemWatcher(); fileWatcher.BeginInit(); fileWatcher.IncludeSubdirectories = false; fileWatcher.Filter = "*.txt"; fileWatcher.Path = setting.incomingFolder; fileWatcher.Created += new FileSystemEventHandler(OnFileCreated); fileWatcher.EnableRaisingEvents = true; fileWatcher.EndInit(); }
public IDisposable Watch(DirectoryInfo scriptPath) { var watcher = new FileSystemWatcher(scriptPath.FullName); watcher.BeginInit(); watcher.Path = scriptPath.FullName; watcher.EnableRaisingEvents = true; watcher.Error += OnError; watcher.Changed += OnChanged; watcher.Created += OnCreated; watcher.Deleted += OnDeleted; watcher.Renamed += OnRenamed; watcher.EndInit(); return new Disposable(() => watcher.Dispose()); }
public Watcher(string path, Action<string> receiver) { // important to append the path with a directory separator, // so that stripping works as expected! if (!path.EndsWith(DirectorySeparatorString)) path += DirectorySeparatorString; _path = path; _receiver = receiver; _watcher = new FileSystemWatcher(); _watcher.BeginInit(); _watcher.Filter = string.Empty; _watcher.IncludeSubdirectories = true; _watcher.InternalBufferSize = InitialBufferSize; _watcher.Path = path; _watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite // we want attributes to catch error-fixups | NotifyFilters.Attributes | NotifyFilters.Security; // we assume that size changes are covered by LastWrite // | NotifyFilters.Size; // note: all events are on threadpool threads! _watcher.Created += onCreated; _watcher.Deleted += onDeleted; _watcher.Changed += onChanged; _watcher.Renamed += onRenamed; _watcher.Error += onError; _watcher.EndInit(); _watcher.EnableRaisingEvents = true; }
public static void ListenForChanges(string currentDirectory) { var watcher = new FileSystemWatcher(currentDirectory) { NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite, EnableRaisingEvents = true, IncludeSubdirectories = true, InternalBufferSize = 16777216 }; watcher.BeginInit(); watcher.Changed += watcher_Changed; watcher.Created += watcher_Changed; watcher.Deleted += watcher_Changed; watcher.Renamed += watcher_Changed; watcher.EndInit(); while (true) { // begin event loop for watcher System.Threading.Thread.Sleep(100); ProcessQueueItem(); } }
/// <summary> /// Creates the instance of <see cref="FileSystemWatcher" /> used /// to monitor the file system. /// </summary> /// <returns> /// An instance of <see cref="FileSystemWatcher" /> that will be /// used to monitor the directory for the creation/modification /// of log files. /// </returns> /// <remarks> /// <see cref="CreateFileSystemWatcher" /> will be called from within /// a synchronized context so derived classes should not attempt to /// perform any additional synchronization themselves. /// </remarks> protected virtual FileSystemWatcher CreateFileSystemWatcher() { Contract.Ensures(Contract.Result<FileSystemWatcher>() != null); var watcher = new FileSystemWatcher(); watcher.BeginInit(); watcher.Changed += this.watcher_Changed; watcher.Created += this.watcher_Created; watcher.EnableRaisingEvents = true; watcher.Filter = this.Name + "_*.txt"; watcher.IncludeSubdirectories = false; watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName; watcher.Path = this.Path; watcher.EndInit(); return watcher; }
private void InitLoadBackupJobs() { LoadBackupJobs(); _backupJobsFileSystemWatcher = new FileSystemWatcher(); if (_backupJobsFileSystemWatcher != null) return; _backupJobsFileSystemWatcher = new FileSystemWatcher(GlobalSettings.AppDataSettingsPath); _backupJobsFileSystemWatcher.BeginInit(); _backupJobsFileSystemWatcher.Created += FileSystemWatcherEvent; _backupJobsFileSystemWatcher.Renamed += FileSystemWatcherRenamed; _backupJobsFileSystemWatcher.Deleted += FileSystemWatcherEvent; _backupJobsFileSystemWatcher.Changed += FileSystemWatcherEvent; _backupJobsFileSystemWatcher.IncludeSubdirectories = true; _backupJobsFileSystemWatcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; _backupJobsFileSystemWatcher.EnableRaisingEvents = true; _backupJobsFileSystemWatcher.EndInit(); }
protected override void OnStart(string[] args) { try { Log("Service", "Start"); watcher = new FileSystemWatcher(); watcher.BeginInit(); watcher.IncludeSubdirectories = true; watcher.Path = ResourcePath; watcher.Created += Watcher_Created; watcher.EnableRaisingEvents = true; watcher.EndInit(); Log("Watching", "Start"); Log("Calculating", "Start"); DirectoryInfo info = new DirectoryInfo(ResourcePath); var dirs = info.GetDirectories("视频", SearchOption.AllDirectories); foreach (var dir in dirs) { var files = dir.GetFiles().Where(o => o.Name.EndsWith(".avi", StringComparison.OrdinalIgnoreCase) || o.Name.EndsWith(".mpg", StringComparison.OrdinalIgnoreCase) || o.Name.EndsWith(".mpeg", StringComparison.OrdinalIgnoreCase) || o.Name.EndsWith(".rm", StringComparison.OrdinalIgnoreCase) || o.Name.EndsWith(".rmvb", StringComparison.OrdinalIgnoreCase) || o.Name.EndsWith(".wmv", StringComparison.OrdinalIgnoreCase)).ToList(); var table = engine.OpenXTable<string, ConvertingResource>("Video"); foreach (var file in files) { var path = file.FullName; var target = path.Substring(0, path.LastIndexOf('.')) + TagetExtension; if (!File.Exists(target)) { table[path] = new ConvertingResource { Target = target, Started = false }; Log("Todo", string.Format("{0} --> {1}", path, target)); } } engine.Commit(); } Log("Calculating", "Calculated"); StartConvert(); } catch (Exception exception) { try { watcher.Dispose(); } catch { } Log("Error", exception.StackTrace.ToString(CultureInfo.InvariantCulture)); } }
public void RefreshUploadContent() { ThreadPool.QueueUserWorkItem(delegate (object state) { VGen0 method = null; VGen1 gen2 = null; try { this.CancelUploadSearch = true; while (this.ScanningForUploads) { Thread.Sleep(20); } this.CancelUploadSearch = false; try { this.ScanningForUploads = true; if (!base.Disposing && !base.IsDisposed) { if (method == null) { method = delegate { this.PreviousUploadStatus = Loc.Get("<LOC>Searching for content..."); if (!AdditionalContent.UploadingContent) { this.NodeUploadSearch.Text = this.PreviousUploadStatus; } }; } IAsyncResult result = base.BeginInvoke(method); FileSystemWatcher[] array = new FileSystemWatcher[this.UploadMonitors.Values.Count]; this.UploadMonitors.Values.CopyTo(array, 0); foreach (FileSystemWatcher watcher in array) { if (!Program.Settings.Content.Upload.UploadPaths.Contains(watcher.Path)) { this.UploadMonitors.Remove(watcher.Path); } } foreach (string str in Program.Settings.Content.Upload.UploadPaths.ToArray()) { if (!Directory.Exists(str)) { Program.Settings.Content.Upload.UploadPaths.Remove(str); } } foreach (string str in Program.Settings.Content.Upload.UploadPaths) { if (!this.UploadMonitors.ContainsKey(str)) { FileSystemWatcher watcher = new FileSystemWatcher(str); watcher.BeginInit(); watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; watcher.Created += new FileSystemEventHandler(this.UploadFileAdded); watcher.Deleted += new FileSystemEventHandler(this.UploadFileDeleted); watcher.Renamed += new RenamedEventHandler(this.UploadFileRenamed); watcher.Changed += new FileSystemEventHandler(this.UploadFileChanged); watcher.EndInit(); this.UploadMonitors[str] = watcher; } } foreach (TreeNode node in this.treeViewUpload.Nodes.Find("AvailableUploads", false)) { this.CheckExistence(node); } this.CheckCachedLocations(); foreach (string str in Program.Settings.Content.Upload.UploadPaths) { this.RefreshUploadContent(str); } if (!this.CancelUploadSearch) { List<TreeNode> list = new List<TreeNode>(); foreach (TreeNode node in this.treeViewUpload.Nodes) { TreeNode[] dest = new TreeNode[node.Nodes.Count]; node.Nodes.CopyTo(dest, 0); list.AddRange(dest); } int total = 0; foreach (TreeNode node in list) { if (this.CancelUploadSearch) { return; } if ((node != this.NodeUploadSearch) && (node.Nodes.Count == 0)) { if (base.Disposing || base.IsDisposed) { return; } base.Invoke((VGen1)delegate (object s) { (s as TreeNode).Remove(); }, new object[] { node }); continue; } ContentType tag = node.Tag as ContentType; if (tag != null) { if (base.Disposing || base.IsDisposed) { return; } if (gen2 == null) { gen2 = delegate (object s) { this.TreeRootCount(s as TreeNode); }; } base.Invoke(gen2, new object[] { node }); total += node.Nodes.Count; } } if ((!this.CancelUploadSearch && (result.IsCompleted || result.AsyncWaitHandle.WaitOne(0x7d0, true))) && ((!this.CancelUploadSearch && !base.Disposing) && !base.IsDisposed)) { base.BeginInvoke((VGen0)delegate { this.PreviousUploadStatus = Loc.Get(string.Format(Loc.Get("<LOC>Found {0} content files."), total)); if (!AdditionalContent.UploadingContent) { this.NodeUploadSearch.Text = this.PreviousUploadStatus; } }); } } } } finally { this.ScanningForUploads = false; } } catch (Exception exception) { ErrorLog.WriteLine(exception); this.ScanningForUploads = false; } }); }
protected FileSystemWatcher CreateFileSystemWatcher(string directory) { //Console.WriteLine("Watcher creating {0}", directory); var watcher = new FileSystemWatcher() { Path = directory, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, Filter = FileFilter, IncludeSubdirectories = true }; watcher.BeginInit(); watcher.Changed += OnModified; watcher.Created += OnModified; watcher.Deleted += OnModified; watcher.Renamed += OnModified; watcher.Error += WatcherOnError; watcher.EndInit(); watcher.EnableRaisingEvents = true; //Console.WriteLine("Watcher created {0}", directory); return watcher; }
void InitializeFileSystemWatcher(string path) { if (folderWatcher != null) { folderWatcher.Dispose(); } folderWatcher = new FileSystemWatcher(path, "*.bin"); folderWatcher.BeginInit(); folderWatcher.Changed += OnFolderWatcherChanged; folderWatcher.Created += OnFolderWatcherCreated; folderWatcher.Deleted += OnFolderWatcherDeleted; folderWatcher.EnableRaisingEvents = true; folderWatcher.IncludeSubdirectories = false; folderWatcher.SynchronizingObject = this; folderWatcher.EndInit(); }
static void Main(string[] args) { var path = args.Length == 0 ? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Diablo III\Screenshots" : args[0]; if (args.Length == 3) { Size = new Rectangle(int.Parse(args[1].Split('x')[0]), int.Parse(args[1].Split('x')[1]), int.Parse(args[2].Split('x')[0]), int.Parse(args[2].Split('x')[1])); ResetSize = false; } Console.WriteLine("Registering filesystem events. ({0})", path); watcher = new FileSystemWatcher(path, "*.jpg"); watcher.BeginInit(); watcher.EnableRaisingEvents = true; watcher.Created += WatcherOnCreated; watcher.EndInit(); while (true) { Thread.Sleep(1000); } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent () { this.ObserveImportDirectoryFileSystemWatcher = (new System.IO.FileSystemWatcher()); ObserveImportDirectoryFileSystemWatcher.BeginInit(); // // ObserveImportDirectoryFileSystemWatcher // this.ObserveImportDirectoryFileSystemWatcher.EnableRaisingEvents = true; this.ObserveImportDirectoryFileSystemWatcher.Filter = "*.av*"; this.ObserveImportDirectoryFileSystemWatcher.NotifyFilter = (System.IO.NotifyFilters)((((System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName) | System.IO.NotifyFilters.Size) | System.IO.NotifyFilters.LastWrite)); this.ObserveImportDirectoryFileSystemWatcher.Created += new FileSystemEventHandler(ObserveImportDirectoryFileSystemWatcher_Created); this.ObserveImportDirectoryFileSystemWatcher.Deleted += new FileSystemEventHandler(ObserveImportDirectoryFileSystemWatcher_Deleted); this.ObserveImportDirectoryFileSystemWatcher.Renamed += new RenamedEventHandler(ObserveImportDirectoryFileSystemWatcher_Renamed); this.ObserveImportDirectoryFileSystemWatcher.Changed += new FileSystemEventHandler(ObserveImportDirectoryFileSystemWatcher_Changed); // PreparePlayableMaterialDLL // //this.CanPauseAndContinue = true; //this.ServiceName = "PreparePlayableMaterialDLL"; ObserveImportDirectoryFileSystemWatcher.EndInit(); }
public void AttachToSystem() { #if MONO && DEBUG return; #endif if (_fileSystemWatcher != null) return; _fileSystemWatcher = new FileSystemWatcher(ProjectPath); _fileSystemWatcher.BeginInit(); _fileSystemWatcher.Created += FileSystemWatcherCreated; _fileSystemWatcher.Renamed += FileSystemWatcherRenamed; _fileSystemWatcher.Deleted += FileSystemWatcherDeleted; _fileSystemWatcher.IncludeSubdirectories = true; _fileSystemWatcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName; _fileSystemWatcher.EnableRaisingEvents = true; _fileSystemWatcher.EndInit(); }
/// <summary> /// Initializes the manager /// </summary> /// <returns>TRUE for success; FALSE otherwise</returns> public bool InitMgr() { // Get the manager settings try { m_MgrSettings = new clsMgrSettings(); } catch { // Failures are logged by clsMgrSettings return false; } // Update the cached manager name m_MgrName = m_MgrSettings.GetParam("MgrName"); // Set up the loggers var logFileName = m_MgrSettings.GetParam("logfilename"); // LogLevel is 1 to 5: 1 for Fatal errors only, 4 for Fatal, Error, Warning, and Info, and 5 for everything including Debug messages var debugLevel = int.Parse(m_MgrSettings.GetParam("debuglevel")); clsLogTools.CreateFileLogger(logFileName, debugLevel); var logCnStr = m_MgrSettings.GetParam("connectionstring"); clsLogTools.CreateDbLogger(logCnStr, "SpaceManager: " + m_MgrName); // Make initial log entry var msg = "=== Started Space Manager V" + System.Windows.Forms.Application.ProductVersion + " ===== "; clsLogTools.WriteLog(clsLogTools.LoggerTypes.LogFile, clsLogTools.LogLevels.INFO, msg); // Setup the message queue m_MsgQueueInitSuccess = false; m_MsgHandler = new clsMessageHandler(); m_MsgHandler.BrokerUri = m_MsgHandler.BrokerUri = m_MgrSettings.GetParam("MessageQueueURI"); m_MsgHandler.CommandQueueName = m_MgrSettings.GetParam("ControlQueueName"); m_MsgHandler.BroadcastTopicName = m_MgrSettings.GetParam("BroadcastQueueTopic"); m_MsgHandler.StatusTopicName = m_MgrSettings.GetParam("MessageQueueTopicMgrStatus"); m_MsgHandler.MgrSettings = m_MgrSettings; // Initialize the message queue // Start this in a separate thread so that we can abort the initialization if necessary InitializeMessageQueue(); if (m_MsgQueueInitSuccess) { //Connect message handler events m_MsgHandler.CommandReceived += OnCommandReceived; m_MsgHandler.BroadcastReceived += OnBroadcastReceived; } // Setup a file watcher for the config file var fInfo = new FileInfo(System.Windows.Forms.Application.ExecutablePath); m_FileWatcher = new FileSystemWatcher(); m_FileWatcher.BeginInit(); m_FileWatcher.Path = fInfo.DirectoryName; m_FileWatcher.IncludeSubdirectories = false; m_FileWatcher.Filter = m_MgrSettings.GetParam("configfilename"); m_FileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size; m_FileWatcher.EndInit(); m_FileWatcher.EnableRaisingEvents = true; // Subscribe to the file watcher Changed event m_FileWatcher.Changed += FileWatcherChanged; // Set up the tool for getting tasks m_Task = new clsSpaceMgrTask(m_MgrSettings); // Set up the status file class var statusFileNameLoc = Path.Combine(fInfo.DirectoryName, "Status.xml"); m_StatusFile = new clsStatusFile(statusFileNameLoc) { //Note: Might want to put this back in someday //MonitorUpdateRequired += new StatusMonitorUpdateReceived(OnStatusMonitorUpdateReceived); LogToMsgQueue = bool.Parse(m_MgrSettings.GetParam("LogStatusToMessageQueue")), MgrName = m_MgrName, MgrStatus = EnumMgrStatus.Running }; m_StatusFile.WriteStatusFile(); // Set up the status reporting time m_StatusTimer = new System.Timers.Timer(); m_StatusTimer.BeginInit(); m_StatusTimer.Enabled = false; m_StatusTimer.Interval = 60000; // 1 minute m_StatusTimer.EndInit(); m_StatusTimer.Elapsed += m_StatusTimer_Elapsed; // Get the most recent job history var historyFile = Path.Combine(m_MgrSettings.GetParam("ApplicationPath"), "History.txt"); if (File.Exists(historyFile)) { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (var sr = new StreamReader(historyFile)) { String line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { if (line.Contains("RecentJob: ")) { var tmpStr = line.Replace("RecentJob: ", ""); m_StatusFile.MostRecentJobInfo = tmpStr; break; } } } } catch (Exception ex) { LogError("Exception reading status history file", ex); } } // Set up the storage operations class m_StorageOps = new clsStorageOperations(m_MgrSettings); // Everything worked! return true; }