file watcher c#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all i have this problem: how can i develop an application which react to a
file creation? i mean how can i use something like a SystemFileWatcher of the
Framework .Net, because this class is not in the compact framework.

I have read that you have to use the FindFirstChangeNotification of the
windows api, but i have no idea how to make a wrapper class for this, please
help me...

thanks
 
This should get you a good start. The P/Invoke statements work. This is
going to need some work. Better error handling and such. But it will help
you get gonig.

public static class FileWatcher
{
[DllImport("coredll.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindFirstChangeNotification(string
lpPathName, bool bWatchSubtree, int dwNotifyFilter);

[DllImport("coredll.dll")]
private static extern int WaitForSingleObject(IntPtr hHandle, int
dwMilliseconds);

[DllImport("coredll.dll")]
[return:MarshalAs(UnmanagedType.Bool)]
private static extern bool FindCloseChangeNotification(IntPtr
hChangeHandle);

private const int SMB_FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001;
private const int SMB_FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002;
private const int SMB_FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004;
private const int SMB_FILE_NOTIFY_CHANGE_SIZE = 0x00000008;
private const int SMB_FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010;

private const long INVALID_HANDLE_VALUE = -1;
private const int INFINITE = -1;

public static int? WaitForFileCreation(string fileName)
{
IntPtr handle = FindFirstChangeNotification(fileName, false,
SMB_FILE_NOTIFY_CHANGE_FILE_NAME);
if ( handle != new IntPtr(INVALID_HANDLE_VALUE) )
{
WaitForSingleObject(handle, INFINITE);
FindCloseChangeNotification(handle);
return null;
}
else
{
return Marshal.GetLastWin32Error();
}
}
}
 
Back
Top