我已经精简了MSDN 示例以专注于文件创建,因为这是文件上传到 FTP 服务器时唯一感兴趣的事件。
必须为此代码示例安装响应式扩展才能在 Visual Studio 2012 中工作。
class Program
{
static void Main()
{
// Create a FileSystemWatcher to watch the FTP incoming directory for creation of listing file
using (var watcher = new FileSystemWatcher(@"C:\FTP-Data\Incoming", "*.lst"))
{
// Use the FromEvent operator to setup a subscription to the Created event.
//
// The first lambda expression performs the conversion of Action<FileSystemEventArgs>
// to FileSystemEventHandler. The FileSystemEventHandler just calls the handler
// passing the FileSystemEventArgs.
//
// The other lambda expressions add and remove the FileSystemEventHandler to and from
// the event.
var fileCreationObservable = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(
UseOnlyTheSecondArgument,
fsHandler => watcher.Created += fsHandler,
fsHandler => watcher.Created -= fsHandler);
fileCreationObservable.Subscribe(ActionWhenFileIsUploaded);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press ENTER to quit the program...\n");
Console.ReadLine();
}
}
private static void ActionWhenFileIsUploaded(FileSystemEventArgs args)
{
Console.WriteLine("{0} was created.", args.FullPath);
// TODO
// 1. Deduce original file name from the listing file info
// 2. Consume the data file
// 3. Remove listing file
}
private static FileSystemEventHandler UseOnlyTheSecondArgument(Action<FileSystemEventArgs> handler)
{
return (object sender, FileSystemEventArgs e) => handler(e);
}
}
我仍在研究将可观察的列表文件转换为可观察的实际数据文件的细节。敬请关注。