The following class is a wrapper for the System.IO.FileSystemWatcher and converts the FileSystem events into observables. You need to download and reference the Reactive Extensions for .NET (Rx) to use this code:
public class FileSystemObservable
{
private readonly FileSystemWatcher _fileSystemWatcher;
public FileSystemObservable(string directory,
string filter, bool includeSubdirectories)
{
_fileSystemWatcher =
new FileSystemWatcher(directory, filter)
{
EnableRaisingEvents = true,
IncludeSubdirectories = includeSubdirectories
};
ChangedFiles =
Observable.FromEvent<FileSystemEventHandler,
FileSystemEventArgs>
(h => h.Invoke,
h => _fileSystemWatcher.Changed += h,
h => _fileSystemWatcher.Changed -= h)
.Select(x => x.EventArgs);
CreatedFiles =
Observable.FromEvent<FileSystemEventHandler,
FileSystemEventArgs>
(h => h.Invoke,
h => _fileSystemWatcher.Created += h,
h => _fileSystemWatcher.Created -= h)
.Select(x => x.EventArgs);
DeletedFiles =
Observable.FromEvent<FileSystemEventHandler,
FileSystemEventArgs>
(h => h.Invoke,
h => _fileSystemWatcher.Deleted += h,
h => _fileSystemWatcher.Deleted -= h)
.Select(x => x.EventArgs);
RenamedFiles =
Observable.FromEvent<RenamedEventHandler,
RenamedEventArgs>
(h => h.Invoke,
h => _fileSystemWatcher.Renamed += h,
h => _fileSystemWatcher.Renamed -= h)
.Select(x => x.EventArgs);
Errors =
Observable.FromEvent<ErrorEventHandler, ErrorEventArgs>
(h => h.Invoke,
h => _fileSystemWatcher.Error += h,
h => _fileSystemWatcher.Error -= h)
.Select(x => x.EventArgs);
}
/// <summary>
/// Gets or sets the errors.
/// </summary>
/// <value>The errors.</value>
public IObservable<ErrorEventArgs> Errors
{ get; private set; }
/// <summary>
/// Gets the changed files.
/// </summary>
/// <value>The changed files.</value>
public IObservable<FileSystemEventArgs> ChangedFiles
{ get; private set; }
/// <summary>
/// Gets the created files.
/// </summary>
/// <value>The created files.</value>
public IObservable<FileSystemEventArgs> CreatedFiles
{ get; private set; }
/// <summary>
/// Gets the deleted files.
/// </summary>
/// <value>The deleted files.</value>
public IObservable<FileSystemEventArgs> DeletedFiles
{ get; private set; }
/// <summary>
/// Gets the renamed files.
/// </summary>
/// <value>The renamed files.</value>
public IObservable<RenamedEventArgs> RenamedFiles
{ get; private set; }
}
Now we can use the observable and can easily create meta-events:
IDisposable writer =
new FileSystemObservable(@"d:\Test\", "*.*", false)
.CreatedFiles
.Where(x => (new FileInfo(x.FullPath)).Length > 0)
// … you can do much more with the combinators
.Select(x => x.Name)
.Subscribe(Console.WriteLine);