Created
February 8, 2012 16:46
-
-
Save mauricio/1770988 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Threading; | |
namespace FileWatcherSample | |
{ | |
class MainClass | |
{ | |
public static void Main (string[] args) | |
{ | |
string directory = Path.Combine (Path.GetTempPath (), "file-watcher-sample"); | |
try { | |
Directory.CreateDirectory (directory); | |
FileSystemWatcher watcher = new FileSystemWatcher (); | |
watcher.Path = directory; | |
watcher.Filter = "*.*"; | |
watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size ; | |
watcher.Changed += OnFileEvent; | |
watcher.Renamed += OnFileEvent; | |
watcher.Created += OnFileEvent; | |
watcher.Deleted += OnFileEvent; | |
watcher.IncludeSubdirectories = true; | |
watcher.InternalBufferSize = 10; | |
watcher.EnableRaisingEvents = true; | |
Directory.CreateDirectory (Path.Combine (directory, "Inbox")); | |
Directory.CreateDirectory (Path.Combine (directory, "Inbox", "something")); | |
CreateFile (directory, "my-file.txt"); | |
CreateFile (directory, "my-file.txt"); | |
CreateFile (directory, "Inbox", "my-file.txt"); | |
Thread.Sleep (TimeSpan.FromSeconds (5)); | |
} finally { | |
Directory.Delete (directory, true); | |
} | |
} | |
public static void OnFileEvent (object sender, FileSystemEventArgs args) | |
{ | |
Console.WriteLine ("{0} - {1} - {2}", args.ChangeType, args.FullPath, args.Name); | |
} | |
public static void CreateFile (params string[] elements) | |
{ | |
using (FileStream stream = new FileStream( Path.Combine( elements ), FileMode.OpenOrCreate )) { | |
using (StreamWriter writer = new StreamWriter(stream)) { | |
writer.WriteLine( "this is my piece - " + new Random().NextDouble() ); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment