//srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。 //保存ファイル名は「ファイル名-ページ番号.pdf」とする。 //分割したページ数を返す。 public List<string> Run(string src, string dest) { // srcで渡されたファイルが存在するか? if (!File.Exists(src)) { throw new FileNotFoundException(); } // destで渡されたフォルダが存在するか? if (!Directory.Exists(dest)) { throw new DirectoryNotFoundException(); } var reader = new iTextSharp.text.pdf.PdfReader(src); string file_name = Path.GetFileNameWithoutExtension(src); int digit = reader.NumberOfPages.ToString().Length; var app_name = new MainForm(); // 一時フォルダにpdfを作成してdestにコピー。 // その際上書き確認を行う。 System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); if (del.Exists) del.Delete(true); System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); tmp.Create(); for (int i = 1; i <= reader.NumberOfPages; i++) { var doc = new iTextSharp.text.Document(); var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit); var dest_name = String.Format(dest_tmp, tmp, file_name, i); var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create)); doc.Open(); copy.AddPage(copy.GetImportedPage(reader, i)); doc.Close(); } // コピーしたファイルを監視する Ret.list.Clear(); var watcher = new System.IO.FileSystemWatcher(); watcher.Path = dest; watcher.Filter = "*.pdf"; watcher.Changed += new FileSystemEventHandler(changed); watcher.Created += new FileSystemEventHandler(changed); watcher.EnableRaisingEvents = true; FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs); watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; tmp.Delete(true); reader.Close(); return Ret.list; }
private void InitFileSystemWatcher() { if (_fsWatcher != null) { _fsWatcher.Dispose(); _fsWatcher = null; } _fsWatcher = new FileSystemWatcher(PluginSettings.Instance.UserScriptsFolder, "*.cs"); _fsWatcher.IncludeSubdirectories = false; _fsWatcher.Created += new FileSystemEventHandler(_fsWatcher_Created); _fsWatcher.Renamed += new RenamedEventHandler(_fsWatcher_Renamed); _fsWatcher.Deleted += new FileSystemEventHandler(_fsWatcher_Deleted); _fsWatcher.EnableRaisingEvents = true; }
/// <summary> /// Filename is filename with full path /// </summary> /// <param name="fileName"></param> public void StartWatching(string fileName) { this.fileName = fileName + ".wo"; m_bIsWatching = true; if (m_Watcher != null) { m_Watcher.EnableRaisingEvents = false; m_Watcher.Dispose(); } m_Watcher = new System.IO.FileSystemWatcher(Path.GetDirectoryName(fileName), Path.GetFileName(fileName)); m_Watcher.NotifyFilter = NotifyFilters.LastWrite; m_Watcher.Changed += new FileSystemEventHandler(OnChanged); m_Watcher.EnableRaisingEvents = true; }
public void Dispose() { if (_fsw != null) { _fsw.Dispose(); } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { _watcher.EnableRaisingEvents = false; Logger.Write($"Stopped watching {_sourcePath} for {_name}:{_containerPath}"); lock (_executingProcess) { foreach (var process in _executingProcess) { process.WaitForExit(); } } if (!disposedValue) { if (disposing) { _watcher.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
//based on code from https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1 private void BeginWatch() { // Create a new FileSystemWatcher and set its properties. _watcher = new System.IO.FileSystemWatcher(); _watcher.Path = PathToWatch; _watcher.IncludeSubdirectories = true; // 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; // Example if we wanted to restrict file types //watcher.Filter = "*.txt"; // Add event handlers. _watcher.Changed += OnChanged; _watcher.Created += OnChanged; _watcher.Deleted += OnChanged; _watcher.Renamed += OnChanged; // Begin watching. _watcher.EnableRaisingEvents = true; // Wait for the user to quit the program. while (ShouldRun == true) { ; } _watcher.Dispose(); }
void DisposeFileWatcher(FileSystemWatcher fileWatcher) { fileWatcher.EnableRaisingEvents = false; fileWatcher.Changed -= BranchWatcher_Changed; fileWatcher.Renamed -= BranchWatcher_Renamed; fileWatcher.Dispose(); }
public static IObservable<string> WatchForChanges(string path,string filter,bool recursive) { var isDirectory = new DirectoryInfo(path).Exists; recursive = isDirectory && recursive; var fileSystemWatcher = new FileSystemWatcher(path) { Filter = filter, IncludeSubdirectories = recursive }; fileSystemWatcher.EnableRaisingEvents = true; var observable = fileSystemWatcher.AsObservable() .ObserveOn(TaskPoolScheduler.Default) .Select(e => e.FullPath) .Buffer(TimeSpan.FromSeconds(1)) .Where(e => e.Any()) .Select(e => e.Distinct()) .SelectMany(e => e); var connectableObservable = observable.Publish(); connectableObservable.Connect(); connectableObservable.Subscribe((v) => log.Info("Detected file system change, root: {0}, change: {1}",path,v), (ex) => fileSystemWatcher.Dispose(), fileSystemWatcher.Dispose); return connectableObservable; }
private void Btn_AutoRun_Click(object sender, EventArgs e) { if (v_IsWatching) { v_IsWatching = false; fileSystemWatcherLogs.EnableRaisingEvents = false; fileSystemWatcherLogs.Dispose(); Btn_AutoRun.BackColor = Color.Blue; Btn_AutoRun.Text = "Start Scan"; } else { v_IsWatching = true; Btn_AutoRun.BackColor = Color.Red; Btn_AutoRun.Text = "Stop Scan"; fileSystemWatcherLogs = new System.IO.FileSystemWatcher(); string v_FolderInput = ConfigurationManager.AppSettings["PathInput"].ToString(); fileSystemWatcherLogs.Filter = "*.*"; fileSystemWatcherLogs.Path = v_FolderInput + "\\"; fileSystemWatcherLogs.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; fileSystemWatcherLogs.Changed += new FileSystemEventHandler(OnChanged); //fileSystemWatcherLogs.Created += new FileSystemEventHandler(OnChanged); //fileSystemWatcherLogs.Deleted += new FileSystemEventHandler(OnChanged); //fileSystemWatcherLogs.Renamed += new RenamedEventHandler(OnRenamed); fileSystemWatcherLogs.EnableRaisingEvents = true; } }
public bool StopFTPWatcher() { try { Thread.Sleep(200); //threadReads.Abort(); if (watcher != null) { watcher.EnableRaisingEvents = false; watcher.Created -= new FileSystemEventHandler(OnCreated); watcher.Dispose(); watcher = null; // Form1.log.Info("Watcher Stopped"); } TimerMonitor.Stop(); TimerPending.Stop(); TimerMatch.Stop(); IsRunning = false; return(true); } catch (Exception ex) { //Form1.log.Error("StopFTPWatcher Error", ex); return(false); } }
public void CreateWatcher() { try { if (XmlWatcher != null) { XmlWatcher.Dispose(); } XmlWatcher = new System.IO.FileSystemWatcher(basePath) { Filter = "*.xml", IncludeSubdirectories = true, }; // Event handlers that are watching for specific event XmlWatcher.Created += RaisePopulateFlag; XmlWatcher.Changed += RaisePopulateFlag; XmlWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite; XmlWatcher.EnableRaisingEvents = true; ExceptionOccurred = false; } catch { ExceptionOccurred = true; } }
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 void CreateProjectWatcher() { try { if (XmlWatcher != null) { WprojWatcher.Dispose(); } WprojWatcher = new System.IO.FileSystemWatcher(wwiseProjectPath) { Filter = "*.wproj", IncludeSubdirectories = false, }; // Event handlers that are watching for specific event WprojWatcher.Created += RaiseProjectFlag; WprojWatcher.Changed += RaiseProjectFlag; WprojWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite; WprojWatcher.EnableRaisingEvents = true; ProjectExceptionOccurred = false; } catch { ProjectExceptionOccurred = true; } }
public void StopWatch() { try { if (m_Watcher != null) { m_bIsWatching = false; m_event.Set(); m_Watcher.EnableRaisingEvents = false; m_Watcher.Dispose(); m_Watcher = null; while (m_queue.Count > 0) { UploadFileToServerWithPath(m_queue.Dequeue()); } if (m_dropboxInitialized == true) { m_dropbox.Close(); m_dropboxInitialized = false; } } } catch (Exception err) { throw (new SystemException(err.Message)); } }
public static void Test_FileSystemWatcher_01() { string path = @"c:\Users\Pierre\AppData\Local\Temp"; string filter = "*.cmdline"; _tr.WriteLine("Test_FileSystemWatcher_01 \"{0}\" \"{1}\"", path, filter); FileSystemWatcher watcher = new FileSystemWatcher(path); watcher.Filter = filter; watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; watcher.Changed += new FileSystemEventHandler(watcher_Changed); watcher.Created += new FileSystemEventHandler(watcher_Changed); watcher.Deleted += new FileSystemEventHandler(watcher_Changed); watcher.Renamed += new RenamedEventHandler(watcher_Renamed); try { watcher.EnableRaisingEvents = true; while (true) { //if (_wr.Abort) if (_wr.IsExecutionAborted()) break; } } finally { watcher.EnableRaisingEvents = false; watcher.Dispose(); if (__fs != null) { __fs.Close(); __fs = null; } } }
protected override void OnStop() { m_Watcher.EnableRaisingEvents = false; m_Watcher.Dispose(); this.timer.Stop(); this.timer = null; }
public void Dispose() { if (fsWatcher != null) { fsWatcher.Dispose(); fsWatcher = null; } }
protected override void OnStop() { if (_Watcher != null) { _Watcher.Dispose(); _Watcher = null; } }
private static void DisposeFilesWatcher() { FileWatcher.Changed -= FileWatcher_Changed; FileWatcher.Created -= FileWatcher_Changed; FileWatcher.Renamed -= FileWatcher_Renamed; FileWatcher.EnableRaisingEvents = false; FileWatcher?.Dispose(); FileWatcher = null; }
private static void DisposeFolderWatcher() { FolderWatcher.Created -= FolderWatcher_Created; FolderWatcher.Deleted -= FolderWatcher_Deleted; FolderWatcher.Renamed -= FolderWatcher_Renamed; FolderWatcher.EnableRaisingEvents = false; FolderWatcher?.Dispose(); FolderWatcher = null; }
public void Dispose() { if (_watcher != null) { Stop(); _watcher.Dispose(); _watcher = null; } }
public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { // Check if command is the stop handle. if (1 == e.CommandID) { m_Logger.Log($"Disposing watcher @ {m_Path}", MessageTypeEnum.INFO); m_DirWatcher?.Dispose(); } }
private void _watcher_Deleted(object sender, FileSystemEventArgs e) { if (_watcher == sender) { _watcher.Changed -= _watcher_Changed; _watcher.Deleted -= _watcher_Deleted; _watcher.Dispose(); _watcher = null; } }
/// <summary> /// バックアップスドップ /// </summary> public void Stop() { if (fsw != null) { fsw.EnableRaisingEvents = false; fsw.Dispose(); m_timer.Dispose(); fsw = null; } }
public virtual void Dispose(bool disposing) { if (disposing) { _fsw.EnableRaisingEvents = false; _fsw.Dispose(); _channel?.Writer.Complete(); _channel = null; } }
private void DestroyMirrorModeWatcher() { if (watcher != null) { watcher.Created -= OnChanged; watcher.Changed -= OnChanged; watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; } }
private void btnStop_Click(object sender, RoutedEventArgs e) { watcher.EnableRaisingEvents = false; notifyIcon.Visible = false; btnStop.IsEnabled = false; cts.Cancel(); btnRun.IsEnabled = true; progressBar.Visibility = Visibility.Hidden; lblInfo.Visibility = Visibility.Visible; watcher.Dispose(); }
private void btnWatchFile_Click(object sender, EventArgs e) { if (bIsWatching) { bIsWatching = false; Watcher.EnableRaisingEvents = false; Watcher.Dispose(); btnWatchFile.BackColor = Color.LightSkyBlue; btnWatchFile.Text = "Start Watching"; } else { bIsWatching = true; btnWatchFile.BackColor = Color.Red; btnWatchFile.Text = "Stop Watching"; Watcher = new System.IO.FileSystemWatcher(); if (rdbDir.Checked) { Watcher.Filter = "*.*"; Watcher.Path = txtFile.Text + "\\"; } else { Watcher.Filter = txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\') + 1); Watcher.Path = txtFile.Text.Substring(0, txtFile.Text.Length - Watcher.Filter.Length); } if (chkSubFolder.Checked) { Watcher.IncludeSubdirectories = true; } Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; Watcher.Changed += new FileSystemEventHandler(OnChanged); Watcher.Created += new FileSystemEventHandler(OnChanged); Watcher.Deleted += new FileSystemEventHandler(OnChanged); Watcher.Renamed += new RenamedEventHandler(OnRenamed); Watcher.EnableRaisingEvents = true; string p = txtFile.Text; string h = System.Net.Dns.GetHostName(); String str = @"Data Source=DHWANI\SQLEXPRESS;Initial Catalog=ABCD;Integrated Security=True"; SqlConnection con1 = new SqlConnection(str); con1.Open(); string q = "Insert into Driver(driver_host,driver_path) VALUES (@driver_host,@driver_path)"; SqlCommand cmd1 = new SqlCommand(q, con1); cmd1.Parameters.AddWithValue("@driver_host", h); cmd1.Parameters.AddWithValue("@driver_path", p); cmd1.ExecuteNonQuery(); } }
private void button2_Click_1(object sender, EventArgs e)//監視を終了 { watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; //状態を表示 StatusLabel.Text = "監視おわり( ˘ω˘)"; UnSelect(); //終了を押せなくして開始を押せるように MonitoringEndButton.Enabled = false; MonitoringStartButton.Enabled = true; }
public void Dispose() { // Dispose if (_fileSystemWatcher != null) { _fileSystemWatcher.Dispose(); _fileSystemWatcher.EnableRaisingEvents = false; _fileSystemWatcher.Created -= this.FileSystemWatcher_Creating; _fileSystemWatcher.Changed -= this.FileSystemWatcher_Changed; _fileSystemWatcher.Deleted -= this.FileSystemWatcher_Deleted; } }
private void btnWatchFile_Click(object sender, EventArgs e) { if (m_bIsWatching) { m_bIsWatching = false; m_Watcher.EnableRaisingEvents = false; m_Watcher.Dispose(); btnWatchFile.BackColor = Color.LightSkyBlue; btnWatchFile.Text = "Start Watching"; } else { m_bIsWatching = true; btnWatchFile.BackColor = Color.Orange; btnWatchFile.Text = "Stop Watching"; m_Watcher = new System.IO.FileSystemWatcher(); if (rdbDir.Checked) { try { m_Watcher.Filter = "*.*"; m_Watcher.Path = txtFile.Text + "\\"; } catch { MessageBox.Show("폴더가 잘못되었습니다.", "Notice"); return; } } else { //m_Watcher.Filter = listBox1.Text.Substring(listBox1.Text.LastIndexOf('\\') + 1); m_Watcher.Filter = txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\') + 1); //m_Watcher.Path = listBox1.Text.Substring(0, listBox1.Text.Length - m_Watcher.Filter.Length); m_Watcher.Path = txtFile.Text.Substring(0, txtFile.Text.Length - m_Watcher.Filter.Length); } if (chkSubFolder.Checked) { m_Watcher.IncludeSubdirectories = true; } m_Watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.Size; //m_Watcher.NotifyFilter = NotifyFilters.Size; //to avoid update towice at FSW m_Watcher.Filter = "*.*"; m_Watcher.EnableRaisingEvents = true; m_Watcher.Changed += new FileSystemEventHandler(OnChanged); m_Watcher.Created += new FileSystemEventHandler(OnCreated); m_Watcher.Deleted += new FileSystemEventHandler(OnChanged); m_Watcher.Renamed += new RenamedEventHandler(OnRenamed); //m_Watcher.InternalBufferSize = 65536; } }
public void Add(string path, bool includeSubdirectories) { var folderDisposable = new CompositeDisposable(); var watcher = new System.IO.FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = (System.IO.NotifyFilters.LastAccess | System.IO.NotifyFilters.LastWrite | System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName); watcher.Filter = "*"; watcher.IncludeSubdirectories = includeSubdirectories; var changed = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs> (h => (sender, e) => h(e), h => watcher.Changed += h, h => watcher.Changed -= h) .Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path)); var created = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs> (h => (sender, e) => h(e), h => watcher.Created += h, h => watcher.Created -= h) .Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path)); var deleted = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs> (h => (sender, e) => h(e), h => watcher.Deleted += h, h => watcher.Deleted -= h) .Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, null, path)); var renamed = Observable.FromEvent<RenamedEventHandler, RenamedEventArgs> (h => (sender, e) => h(e), h => watcher.Renamed += h, h => watcher.Renamed -= h) .Select(x => new RxFileSystemEventArgs(x.ChangeType, x.FullPath, x.OldFullPath, path)); var subscription = Observable .Merge(changed, created, deleted, renamed) .Subscribe(this.FolderChangedSubject); watcher.EnableRaisingEvents = true; Disposable.Create(() => { watcher.EnableRaisingEvents = false; subscription.Dispose(); watcher.Dispose(); }) .AddTo(this.Watchers, path); }
public async Task Start(IState initialState, Session session, CancellationToken cancellationToken = default(CancellationToken)) { var state = initialState; var profilePath = Path.Combine(Directory.GetCurrentDirectory(), ""); var profileConfigPath = Path.Combine(profilePath, "config"); FileSystemWatcher configWatcher = new FileSystemWatcher(); configWatcher.Path = profileConfigPath; configWatcher.Filter = "config.json"; configWatcher.NotifyFilter = NotifyFilters.LastWrite; configWatcher.EnableRaisingEvents = true; configWatcher.Changed += (sender, e) => { if (e.ChangeType == WatcherChangeTypes.Changed) { session.LogicSettings = new LogicSettings(GlobalSettings.Load("")); configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents; configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents; Logger.Write(" ##### config.json ##### ", LogLevel.Info); } }; do { try { state = await state.Execute(session, cancellationToken); } catch (InvalidResponseException) { session.EventDispatcher.Send(new ErrorEvent { Message = "Niantic Servers unstable, throttling API Calls." }); } catch (OperationCanceledException) { session.EventDispatcher.Send(new ErrorEvent {Message = "Current Operation was canceled."}); state = _initialState; } catch (Exception ex) { session.EventDispatcher.Send(new ErrorEvent {Message = "Pokemon Servers might be offline / unstable. Trying again..."}); Thread.Sleep(1000); session.EventDispatcher.Send(new ErrorEvent { Message = "Error: " + ex }); state = _initialState; } } while (state != null); configWatcher.EnableRaisingEvents = false; configWatcher.Dispose(); }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _solutionWatcher?.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } }
public void Start() { HostedService service = CreateNewAppDomain(); var watcher = new FileSystemWatcher(path); bool wasCalled = false; var @lock = new object(); FileSystemEventHandler handler = (sender, e) => { string extension = Path.GetExtension(e.FullPath); if (extension != ".dll" && extension != ".config" && extension != ".exe") return; watcher.Dispose(); lock (@lock) { if (wasCalled) return; wasCalled = true; logger.WarnFormat("Got change request for {0}, disposing current AppDomain", e.Name); service.Stop(); Thread.Sleep(500); //allow for other events to happen logger.Warn("Restarting..."); Start(); } }; watcher.Deleted += handler; watcher.Changed += handler; watcher.Created += handler; watcher.EnableRaisingEvents = true; current = service; try { service.Start(); } catch (ReflectionTypeLoadException e) { var sb = new StringBuilder(); foreach (var exception in e.LoaderExceptions) { sb.AppendLine(exception.ToString()); } throw new TypeLoadException(sb.ToString(), e); } }
private void button2_Click(object sender, EventArgs e) { try { //監視を終了 watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; textBox1.Text += "\r\n監視終了"; } catch { textBox1.Text += "\r\n監視停止中に終了できません"; } }
public void StopWatch() { try { if (m_Watcher != null) { m_bIsWatching = false; m_Watcher.EnableRaisingEvents = false; m_Watcher.Dispose(); m_Watcher = null; } } catch (Exception err) { throw (new SystemException(err.Message)); } }
protected override void Dispose(bool disposing) { if (disposing) { _cancellationTokenSource?.Cancel(); _cancellationTokenSource?.Dispose(); _containedFSW?.Dispose(); //_onExistedHandler = null; //_onAllChangesHandler = null; //_onCreatedHandler = null; //_onChangedHandler = null; //_onDeletedHandler = null; //_onRenamedHandler = null; //_onErrorHandler = null; } base.Dispose(disposing); }
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 static IObservable<string> WhenPathChanges(string path, string filter) { return Observable.Create<string>(observer => { var watcher = new FileSystemWatcher(path, filter); var changed = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h); var deleted = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Deleted += h, h => watcher.Deleted -= h); var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h, h => watcher.Created -= h); watcher.EnableRaisingEvents = true; return changed .Merge(deleted) .Merge(created) .Select(e => e.EventArgs.FullPath) .Throttle(TimeSpan.FromMilliseconds(100)) .Finally(() => watcher.Dispose()) .Subscribe(observer); }); }
public IObservable<FileEvent> For(string fullFilePath, string extensionFilter) { return Observable.Create<FileEvent>(obs => { var fileName = Path.GetFileName(fullFilePath); var dir = Path.GetDirectoryName(fullFilePath); var watcher = new FileSystemWatcher(dir, extensionFilter); var onCreated = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h, h => watcher.Created -= h) .Select<EventPattern<FileSystemEventArgs>, FileEvent>( args => new FileCreated(args.EventArgs.FullPath, args.EventArgs.Name)); var onChanged = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h) .Select<EventPattern<FileSystemEventArgs>, FileEvent>( args => new FileChanged(args.EventArgs.FullPath, args.EventArgs.Name)); var onRenamed = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(h => watcher.Renamed += h, h => watcher.Renamed -= h) .Select<EventPattern<RenamedEventArgs>, FileEvent>( ev => new FileRenamed(ev.EventArgs.FullPath, ev.EventArgs.Name, ev.EventArgs.OldFullPath, ev.EventArgs.OldName)); var combined = onCreated.Merge(onChanged).Merge(onRenamed) .Where(ev => ev.Name == fileName) .Subscribe(obs); watcher.EnableRaisingEvents = true; return Disposable.Create(() => { combined.Dispose(); watcher.Dispose(); }); }); }
public void Check_how_does_the_file_system_watcher_work_when_creating_file_and_editing_when_watching_at_the_file_size() { var watcher = new FileSystemWatcher(Environment.CurrentDirectory); bool wasRaised = false; watcher.Created += (s, a) => { Console.WriteLine("Created file "); Assert.That(a.Name, Is.EqualTo(name)); wasRaised = true; }; watcher.Changed += (s, a) => Console.WriteLine("Was modified" ); watcher.NotifyFilter = NotifyFilters.FileName| NotifyFilters.Size; watcher.EnableRaisingEvents = true; var stopwatch = new Stopwatch(); Console.WriteLine("Creating"); using (var stream = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { var writer = new StreamWriter(stream); Thread.Sleep(100); stopwatch.Start(); Console.WriteLine("Writing"); for (int i = 0; i < fileSize; i++) { writer.WriteLine("{0}", i); } Thread.Sleep(100); Console.WriteLine("Flushing"); writer.Flush(); Thread.Sleep(100); Console.WriteLine("Disposing"); writer.Dispose(); stopwatch.Stop(); } Console.WriteLine("Time elapsed " + stopwatch.ElapsedMilliseconds); Console.WriteLine("File size " + new FileInfo(name).Length); Thread.Sleep(100); Assert.That(wasRaised); watcher.Dispose(); }
public void SetupWatchers(IEnumerable<string> files) { if (files == null) return; foreach (var file in files) { var fileInfo = new FileInfo(file); if (fileInfo.Directory == null) throw new IOException("File Path has no directory to watch"); if(FileSystemWatchers.ContainsKey(file)) continue; Console.WriteLine("Started watching '{0}' for changes", file); var directoryFullName = fileInfo.Directory.FullName; var fsWatcher = new FileSystemWatcher(directoryFullName, fileInfo.Name); fsWatcher.Changed += FsWatcherChanged; fsWatcher.EnableRaisingEvents = true; FileSystemWatchers[file] = fsWatcher; } var missing = FileSystemWatchers.Keys.Where(f => !files.Contains(f)).ToList(); foreach (var file in missing) { var fsWatcher = FileSystemWatchers[file]; fsWatcher.Changed -= FsWatcherChanged; fsWatcher.Dispose(); FileSystemWatchers.Remove(file); Console.WriteLine("Stopped watching '{0}'", file); } }
//In case of self-host application activation happens immediately unlike iis where activation happens on first request. //So in self-host case, we need a way to block the first request until the application is initialized. In MusicStore application's case, //identity DB creation is pretty much the last step of application setup. So waiting on this event will help us wait efficiently. private static void WaitTillDbCreated(string identityDbName) { var identityDBFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), identityDbName + ".mdf"); if (File.Exists(identityDBFullPath)) { Console.WriteLine("Database file '{0}' exists. Proceeding with the tests.", identityDBFullPath); return; } Console.WriteLine("Watching for the DB file '{0}'", identityDBFullPath); var dbWatch = new FileSystemWatcher(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), identityDbName + ".mdf"); dbWatch.EnableRaisingEvents = true; try { if (!File.Exists(identityDBFullPath)) { //Wait for a maximum of 1 minute assuming the slowest cold start. var watchResult = dbWatch.WaitForChanged(WatcherChangeTypes.Created, 60 * 1000); if (watchResult.ChangeType == WatcherChangeTypes.Created) { Console.WriteLine("Database file created '{0}'. Proceeding with the tests.", identityDBFullPath); } else { Console.WriteLine("Database file '{0}' not created", identityDBFullPath); } } } catch (Exception exception) { Console.WriteLine("Received this exception while watching for Database file {0}", exception); } finally { dbWatch.Dispose(); } }
private FileSystemWatcher CreateDatabaseVerWatcher() { FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dir = DatabasePath; if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = "database.*", NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database.ver FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Deleted += OnDatabaseVerChanged; watcher.Created += OnDatabaseVerChanged; watcher.Changed += OnDatabaseVerChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion. Fall through and find // a parent directory that exists. watcher.Dispose(); watcher = null; } } return null; } }
public FolderMonitor(string path, string pattern, Action<string[]> callback) { if (callback == null || string.IsNullOrWhiteSpace(path)) { return; } if (string.IsNullOrWhiteSpace(pattern)) { pattern = "*.*"; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } mre = new ManualResetEvent(false); watcher = new FileSystemWatcher(path); watcher.Changed += Watcher_Changed; watcher.EnableRaisingEvents = true; Thread th = new Thread(new ThreadStart(() => { try { mre.WaitOne(); while (!isexit) { Thread.Sleep(500); var files = Directory.GetFiles(path, pattern, SearchOption.AllDirectories); if (files.Length > 0) { callback(files); } mre.WaitOne(); } } catch (Exception ex) { log.e(ex); } finally { mre.Dispose(); watcher.Dispose(); isdisposed = true; } })); th.Start(); }
/// <summary> /// Starts the watching path. /// </summary> /// <param name="path">The path.</param> private void StartWatchingPath(string path) { // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel Task.Run(() => { try { var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true }; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { newWatcher.InternalBufferSize = 32767; } newWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Attributes; newWatcher.Created += watcher_Changed; newWatcher.Deleted += watcher_Changed; newWatcher.Renamed += watcher_Changed; newWatcher.Changed += watcher_Changed; newWatcher.Error += watcher_Error; if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; Logger.Info("Watching directory " + path); } else { Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path); newWatcher.Dispose(); } } catch (Exception ex) { Logger.ErrorException("Error watching path: {0}", ex, path); } }); }
/// <summary> /// Starts the watching path. /// </summary> /// <param name="path">The path.</param> private void StartWatchingPath(string path) { // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel Task.Run(() => { var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 }; newWatcher.Created += watcher_Changed; newWatcher.Deleted += watcher_Changed; newWatcher.Renamed += watcher_Changed; newWatcher.Changed += watcher_Changed; newWatcher.Error += watcher_Error; try { if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; Logger.Info("Watching directory " + path); } else { Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary." + path); newWatcher.Dispose(); } } catch (IOException ex) { Logger.ErrorException("Error watching path: {0}", ex, path); } catch (PlatformNotSupportedException ex) { Logger.ErrorException("Error watching path: {0}", ex, path); } }); }
private void StopWatching(FileSystemWatcher watcher) { InternalLogger.Info("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); watcher.EnableRaisingEvents = false; watcher.Dispose(); }
public async Task Lock(string path, Func<Task> action) { using (var autoResetEvent = new AutoResetEvent(false)) { try { using (var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(path)) { EnableRaisingEvents = true }) { fileSystemWatcher.Deleted += (o, e) => { if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path)) autoResetEvent.Set(); }; while (true) { try { using (var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { fileSystemWatcher.Dispose(); autoResetEvent.Dispose(); await action().ConfigureAwait(false); break; } } catch (IOException) { autoResetEvent.WaitOne(); autoResetEvent.Reset(); } } } } finally { File.Delete(path); } } }
private void DisposeNativeWatcher(FileSystemWatcher watcher) { //Console.WriteLine("Watcher disposing {0}", watcher.Path); watcher.EnableRaisingEvents = false; watcher.Changed -= OnModified; watcher.Created -= OnModified; watcher.Deleted -= OnModified; watcher.Renamed -= OnModified; watcher.Error -= WatcherOnError; watcher.Dispose(); //Console.WriteLine("Watcher disposed {0}", watcher.Path); }
/// <summary> /// Tries to initialize the service. /// </summary> /// <returns></returns> private void TryInitializeService() { if (_watching || !_watchedPath.Available) return; try { _watcher = InitializeFileSystemWatcher(_watchedPath.Path.FullName); _watcher.IncludeSubdirectories = true; _watcher.EnableRaisingEvents = true; _watching = true; _notifyTimer = new SystemTimer(EventsConsolidationInterval); _notifyTimer.Elapsed += NotifyTimer_Elapsed; _notifyTimer.Enabled = true; } catch (Exception) { // If something went wrong: dispose both the watcher and the notifytimer. _watching = false; if (_watcher != null) { _watcher.Dispose(); _watcher = null; } if (_notifyTimer != null) { _notifyTimer.Dispose(); _notifyTimer = null; } } RaiseSingleEvent(_watchedPath.Path.FullName, _watcher != null ? FileWatchChangeType.Enabled : FileWatchChangeType.Disabled); }
static void DisposeWatch(FileSystemWatcher watch) { try { watch.EnableRaisingEvents = false; watch.Dispose(); } catch (Exception) { } }
/// <summary> /// Observe String-Line from file like tail -f. /// </summary> /// <param name="encoding">If null, use Encoding.UTF8</param> public static IObservable<string> FromFileTail(string filePath, bool readFromFirstLine = false, Encoding encoding = null) { return Observable.Defer(() => { encoding = encoding ?? Encoding.UTF8; var subject = new Subject<string>(); var fi = new System.IO.FileInfo(filePath); var stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var streamReader = new StreamReader(stream, encoding); try { var firstSource = new List<string>(); if (readFromFirstLine) { while (!streamReader.EndOfStream) { firstSource.Add(streamReader.ReadLine()); } } else { stream.Seek(fi.Length, SeekOrigin.Current); } var readingLock = new object(); var fsw = new FileSystemWatcher(fi.DirectoryName, fi.Name); fsw.NotifyFilter = NotifyFilters.Size; fsw.Changed += (sender, e) => { try { lock (readingLock) { string s; while ((s = streamReader.ReadLine()) != null) { if (s != "") { subject.OnNext(s); } } } } catch (Exception ex) { subject.OnError(ex); } }; fsw.EnableRaisingEvents = true; return firstSource.ToObservable().Concat(subject).Finally(() => { fsw.EnableRaisingEvents = false; fsw.Dispose(); streamReader.Dispose(); stream.Dispose(); }); } catch { streamReader?.Dispose(); stream?.Dispose(); throw; } }); }
void SetWatcher() { SD.MainThread.VerifyAccess(); if (watcher != null) { watcher.EnableRaisingEvents = false; } if (!enabled) return; if (globalDisableCount > 0) return; if (DetectExternalChangesOption == false) return; string fileName = file.FileName; if (string.IsNullOrEmpty(fileName)) return; if (FileUtility.IsUrl(fileName)) return; if (!Path.IsPathRooted(fileName)) return; try { if (watcher == null) { watcher = new FileSystemWatcher(); watcher.SynchronizingObject = SD.MainThread.SynchronizingObject; watcher.Changed += OnFileChangedEvent; watcher.Created += OnFileChangedEvent; watcher.Renamed += OnFileChangedEvent; } watcher.Path = Path.GetDirectoryName(fileName); watcher.Filter = Path.GetFileName(fileName); watcher.EnableRaisingEvents = true; } catch (PlatformNotSupportedException) { if (watcher != null) { watcher.Dispose(); } watcher = null; } catch (FileNotFoundException) { // can occur if directory was deleted externally if (watcher != null) { watcher.Dispose(); } watcher = null; } catch (ArgumentException) { // can occur if parent directory was deleted externally if (watcher != null) { watcher.Dispose(); } watcher = null; } }
void SetWatcher() { WorkbenchSingleton.AssertMainThread(); if (watcher != null) { watcher.EnableRaisingEvents = false; } if (!enabled || FileChangeWatcher.AllChangeWatchersDisabled) return; if (string.IsNullOrEmpty(fileName)) return; if (FileUtility.IsUrl(fileName)) return; if (!Path.IsPathRooted(fileName)) return; try { if (watcher == null) { watcher = new FileSystemWatcher(); if (WorkbenchSingleton.Instance.Workbench != null) watcher.SynchronizingObject = WorkbenchSingleton.Instance.Workbench.SynchronizingObject; watcher.Changed += OnFileChangedEvent; watcher.Created += OnFileChangedEvent; watcher.Renamed += OnFileChangedEvent; } watcher.Path = Path.GetDirectoryName(fileName); watcher.Filter = Path.GetFileName(fileName); watcher.EnableRaisingEvents = true; } catch (PlatformNotSupportedException) { if (watcher != null) { watcher.Dispose(); } watcher = null; } catch (FileNotFoundException) { // can occur if directory was deleted externally if (watcher != null) { watcher.Dispose(); } watcher = null; } catch (ArgumentException) { // can occur if parent directory was deleted externally if (watcher != null) { watcher.Dispose(); } watcher = null; } }
/// <summary> /// Disposes the watcher. /// </summary> /// <param name="watcher">The watcher.</param> private void DisposeWatcher(FileSystemWatcher watcher) { Logger.Info("Stopping directory watching for path {0}", watcher.Path); watcher.EnableRaisingEvents = false; watcher.Dispose(); RemoveWatcherFromList(watcher); }
private FileSystemWatcher CreateLibraryWatcher() { FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher { IncludeSubdirectories = true, Path = _config.LibraryPath, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite }; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Changed += OnChanged; watcher.Renamed += OnRenamed; watcher.EnableRaisingEvents = true; } catch (IOException) { // Raced with directory deletion. We normally handle the // library being deleted by disposing the watcher, but this // occurs in response to an event from the watcher. Because // we never got to start watching, we will just dispose // immediately. if (watcher != null) { watcher.Dispose(); } } catch (ArgumentException ex) { if (watcher != null) { watcher.Dispose(); } Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex); } return watcher; }
private FileSystemWatcher CreateDatabaseDirectoryWatcher() { FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dirName = CommonUtils.GetFileOrDirectoryName(DatabasePath); var dir = Path.GetDirectoryName(DatabasePath); while (CommonUtils.IsValidPath(dir) && !Directory.Exists(dir)) { dirName = CommonUtils.GetFileOrDirectoryName(dir); dir = Path.GetDirectoryName(dir); } if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = dirName, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database directory FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Created += OnDatabaseFolderChanged; watcher.Renamed += OnDatabaseFolderChanged; watcher.Deleted += OnDatabaseFolderChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion watcher.Dispose(); watcher = null; } } return null; } }
private FileSystemWatcher CreateModuleDirectoryWatcherIfDirectoryExists(string directory) { if (!Directory.Exists(directory)) { return null; } FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher(directory) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime, IncludeSubdirectories = true }; watcher.Changed += Watcher_Modified; watcher.Created += Watcher_Modified; watcher.Deleted += Watcher_Modified; watcher.EnableRaisingEvents = true; } catch (Exception ex) { if (watcher != null) { watcher.Dispose(); } if (ex is IOException || ex is ArgumentException) { Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex); } else { throw; } } return watcher; }