Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement filewatcher using Reactive extensions

I am new to Rx and looking to use it in my current project. I am trying to implement a file watcher system. Atleast for now I am only interested in file Creation event. But I am getting "Value cannot be null error message" when trying to run below code. Please could someone help me out with below code.

class Program
{
    static void Main(string[] args)
    {
        IDisposable writer = new FileSystemObservable(@"D:\Code\Rx\Dropbox\", "*.*", false)
                            .CreatedFiles
                            .Where(x => (new FileInfo(x.FullPath)).Length > 0)
                            .Select(x => x.Name)
                            .Subscribe(Console.WriteLine);
        Console.ReadLine();
    }
}


class FileSystemObservable
{
    private readonly FileSystemWatcher fileSystemWatcher;

    public FileSystemObservable(string directory, string filter, bool includeSubdirectories)
    {
        fileSystemWatcher = new FileSystemWatcher(directory, filter)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = includeSubdirectories
            };

        CreatedFiles = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>
                (h => fileSystemWatcher.Created += h,
                h => fileSystemWatcher.Created -= h)
                .Select(x => new { x.EventArgs }) as IObservable<FileSystemEventArgs>;

        Errors = Observable.FromEventPattern<ErrorEventHandler, ErrorEventArgs>
                (h => fileSystemWatcher.Error += h,
                h => fileSystemWatcher.Error -= h)
                .Select(x => new { x.EventArgs }) as IObservable<ErrorEventArgs>;
    }

    public IObservable<ErrorEventArgs> Errors { get; private set; }

    public IObservable<FileSystemEventArgs> CreatedFiles { get; private set; }
}
like image 408
Narayan Akhade Avatar asked Dec 02 '12 14:12

Narayan Akhade


1 Answers

The result of the

Select(x => new { x.EventArgs }) as IObservable<ErrorEventArgs> 

and

.Select(x => new { x.EventArgs }) as IObservable<FileSystemEventArgs>;

lines will always return null.

The type of Select(x => new { x.EventArgs }) is IObservable<'a> where 'a is some anonymous type.

You should instead use:

CreatedFiles = 
    Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
        h => fileSystemWatcher.Created += h,
        h => fileSystemWatcher.Created -= h)
    .Select(x => x.EventArgs);

Errors = 
    Observable.FromEventPattern<ErrorEventHandler, ErrorEventArgs>(
        h => fileSystemWatcher.Error += h,
        h => fileSystemWatcher.Error -= h)
    .Select(x => x.EventArgs);
like image 105
Lee Avatar answered Oct 16 '22 20:10

Lee