Monday, July 30, 2012

How to use FileSystemWatcher class ?

Here is the sample code ,,just try it,,,

working properly


code:


namespace FileMonitor  
{ 
    public interface EventsList 
    { 
        void OnRenamed(object source, RenamedEventArgs e); 
        void OnChanged(object source, FileSystemEventArgs e); 
    } 
      
    public  class MonitorEngine  
    { 
        private String path; 
        private EventsList events = null; 
     
        public MonitorEngine(String path,EventsList ev) 
        { 
            this.events=ev; 
            this.path=path; 
        } 
        public void WatcherFiles() 
        { 
            FileSystemWatcher watcher = new FileSystemWatcher(); 
            try 
            { 
                watcher.Path = path; 
                watcher.IncludeSubdirectories=true; 
            } 
            catch(ArgumentException ex)  
            { 
                MessageBox.Show(ex.Message); 
                return; 
            } 
             
            // setup what we are looking for 
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite| 
                                   NotifyFilters.FileName  | NotifyFilters.DirectoryName; 
             
            watcher.Filter = "*.*"; 
             
            // Add event handlers. 
            watcher.Changed += new FileSystemEventHandler(events.OnChanged); 
            watcher.Created += new FileSystemEventHandler(events.OnChanged); 
            watcher.Deleted += new FileSystemEventHandler(events.OnChanged); 
            watcher.Renamed += new RenamedEventHandler(events.OnRenamed); 
         
            // Begin watching the directory. 
            watcher.EnableRaisingEvents = true;  
             
        } 
    } 
} 

No comments: