Reputation: 828
I want to watch a directory for file changes (create, edit, rename, delete) and do something, such as calling a function, when a change is detected. From what I can tell, FileSystemWatcher should do this. However, there is no sample code for F# on the documentation page, and elsewhere on the web seems scarce as well.
From what I've found, the following is at least part of the answer:
let fileSystemWatcher = new FileSystemWatcher()
fileSystemWatcher.Path <- @"C:\temp" // I'm actually using a variable here
fileSystemWatcher.NotifyFilter <- NotifyFilters.LastWrite
fileSystemWatcher.EnableRaisingEvents <- true
fileSystemWatcher.IncludeSubdirectories <- true
fileSystemWatcher.Changed.Add(fun _ -> printfn "changed")
fileSystemWatcher.Created.Add(fun _ -> printfn "created")
fileSystemWatcher.Deleted.Add(fun _ -> printfn "deleted")
fileSystemWatcher.Renamed.Add(fun _ -> printfn "renamed")
That doesn't actually do anything, however. Some posts seem to have an Async loop to react to events, but if I use the code snippets from there F# tells me that Async.AwaitObservable
is undefined.
I'd appreciate it if someone could provide a complete example of FileSystemWatcher's correct usage.
Upvotes: 2
Views: 1426
Reputation: 13577
Works fine for me in FSI.
Drop the NotifyFilter
bit - you're overwriting the default settings (which do include LastWrite
anyway), and some of the events you care about are not being raised. NotifyFilter
is an antiquated enum-flag-style field, so you can add a new value there like this:
watcher.NotifyFilter <- watcher.NotifyFilter ||| NotifyFilters.LastWrite
You don't need an async loop per se - in the example you linked to it just replaces the standard event handlers that you are already using. But if you want to use Async.AwaitObservable
, look up FSharpx on nuget.
Upvotes: 1