views:

429

answers:

8

Hello, I want to know when a new file is created on a specific directory, Instead of scanning the directory from time to time, I understand that there is a way to make the O.S tell my program that a new file was created. how does it work?

Thanks

Edit: as suggested below, this is similar to http://stackoverflow.com/questions/61253/how-to-be-notified-of-file-directory-change-in-c-c-ideally-using-posix

+1  A: 

Using .Net on Windows (not sure about Linux/mono) you can use a FileSsytemWatcher to watch for new files and raise events when they are created.

From MSDN:

Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

MSDN Page

ck
Will FileSystemWatcher watch folders recursively?
Geo
+1  A: 

With Mac OS X, this functionality is part of the Spotlight API.

Thomas L Holaday
+2  A: 

FileSystemWatcher is the answer - and it works recursively.

There's an example here (search for FileSystemWatcher)

Joe Albahari
+15  A: 

Depends on which OS.

On Windows, the base API would be Directory Change Notifications.

Since you mention Linux in the tags, this would be the inotify API.

To add to the OS X answer, as of 10.5, you want the FSEvents API.

Sii
+7  A: 

Under Linux, check out Inotify.

Haakon
+1  A: 

The Windows API provides facilities for monitoring the file system - there's an example here http://msdn.microsoft.com/en-us/library/aa365261%28VS.85%29.aspx

anon
+4  A: 

http://stackoverflow.com/questions/61253/how-to-be-notified-of-file-directory-change-in-c-c-ideally-using-posix

or search for inotify in stackoverflow you will get lots of ideas

DanM
+2  A: 

FAM provides a consistent file-watching interface across all UNIXes. On Linux, the back-end daemon may be replaced by Gamin, but a program linked with FAM will work with Gamin just fine. (Behind the scenes, FAM may be using polling, and Gamin may be using inotify or dnotify or kqueue, but you shouldn't need to worry about the implementation.)

OS X.5 has FSEvents, which is very different in that it monitors the whole system instead of specified files and directories, but would also satisfy your needs.

On Windows, see Find(First|Next|Close)ChangeNotification or ReadDirectoryChanges.

ephemient