Created
November 21, 2014 07:11
-
-
Save peace2048/2ae7508b264ab41726e2 to your computer and use it in GitHub Desktop.
FileSystemWatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Reactive; | |
using System.Reactive.Disposables; | |
using System.Reactive.Linq; | |
using System.Reactive.Subjects; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var w = new ObservabeFileSystemWatcher(@"\\10.0.0.7\ZPCommon"); | |
var d = w.Catch(w.DelaySubscription(TimeSpan.FromSeconds(3)).Retry()) | |
.Subscribe( | |
arg => Console.WriteLine(arg.FullPath + " " + arg.ChangeType), | |
except => Console.WriteLine(except.ToString())); | |
Console.ReadLine(); | |
d.Dispose(); | |
Console.ReadLine(); | |
} | |
} | |
class ObservabeFileSystemWatcher : IObservable<FileSystemEventArgs> | |
{ | |
public ObservabeFileSystemWatcher() | |
{ | |
} | |
public ObservabeFileSystemWatcher(string path) | |
{ | |
this.Path = path; | |
} | |
public ObservabeFileSystemWatcher(string path, string filter) | |
{ | |
this.Path = path; | |
this.Filter = filter; | |
} | |
public bool? IncludeSubdirectories { get; set; } | |
public NotifyFilters? NotifyFilter { get; set; } | |
public string Filter { get; set; } | |
public string Path { get; set; } | |
#region IObservable<FileSystemEventArgs> メンバー | |
public IDisposable Subscribe(IObserver<FileSystemEventArgs> observer) | |
{ | |
Console.WriteLine("subscrive"); | |
var watcher = new FileSystemWatcher(); | |
watcher.Path = this.Path; | |
if (this.Filter != null) watcher.Filter = this.Filter; | |
if (this.IncludeSubdirectories.HasValue) watcher.IncludeSubdirectories = this.IncludeSubdirectories.Value; | |
if (this.NotifyFilter.HasValue) watcher.NotifyFilter = this.NotifyFilter.Value; | |
watcher.EnableRaisingEvents = true; | |
return new CompositeDisposable( | |
watcher, | |
Observable.Merge( | |
Observable.FromEventPattern<FileSystemEventArgs>(watcher, "Changed"), | |
Observable.FromEventPattern<FileSystemEventArgs>(watcher, "Created"), | |
Observable.FromEventPattern<FileSystemEventArgs>(watcher, "Deleted"), | |
Observable.FromEventPattern<FileSystemEventArgs>(watcher, "Renamed"), | |
Observable.FromEventPattern<ErrorEventArgs>(watcher, "Error") | |
.Select<EventPattern<ErrorEventArgs>, EventPattern<FileSystemEventArgs>>(_ => | |
{ | |
var e = _.EventArgs.GetException(); | |
Console.WriteLine(e.ToString()); | |
throw e; | |
})) | |
.Select(_ => _.EventArgs) | |
.Subscribe(observer)); | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment