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; }
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With