如何使用Reactive扩展实现filewatcher

时间:2012-12-02 14:20:52

标签: c# system.reactive

我是Rx的新手并希望在我当前的项目中使用它。我正在尝试实现文件观察系统。至少我现在只对文件创建活动感兴趣。但是当我尝试在代码下运行时,我得到“值不能为空错误消息”。 请有人帮我解决下面的代码。

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; }
}

1 个答案:

答案 0 :(得分:5)

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

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

行将始终返回null。

Select(x => new { x.EventArgs })的类型为IObservable<'a>,其中'a是匿名类型。

您应该使用:

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);