Description : We can watch particular folder. If any files created,accessed,changed or deleted we can get that information. This code will very useful for log process.
Name spaces
using System; using System.Collections.Generic; using System.Text; using System.IO;
Code Segment
namespace ConsoleApplication1 { public class Program { static void Main(string[] args) { FileSystemWatcher MyFileSystemWatcher = new FileSystemWatcher(); try { MyFileSystemWatcher.Path = @"D:\Nathan"; } catch (ArgumentException ex) { Console.WriteLine(ex.Message); return; }
MyFileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
MyFileSystemWatcher.Filter = "*.txt";
MyFileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged); MyFileSystemWatcher.Created += new FileSystemEventHandler(OnChanged); MyFileSystemWatcher.Deleted += new FileSystemEventHandler(OnChanged); MyFileSystemWatcher.Renamed += new RenamedEventHandler(OnRenamed); MyFileSystemWatcher.EnableRaisingEvents = true;
Console.WriteLine(@"Press 'q' to quit app."); while (Console.Read() != 'q') ; } private static void OnChanged(object source, FileSystemEventArgs e) { Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType); }
private static void OnRenamed(object source, RenamedEventArgs e) { Console.WriteLine("File: {0} renamed to\n{1}", e.OldFullPath, e.FullPath); } } }
1. Create instance of MyFileSystemWatcher 2. Add the NotifyFilter 3. Add the events 4. Run the application
by Nathan
|
No responses found. Be the first to respond and make money from revenue sharing program.
|