Csharp/C Sharp/File Stream/FileSystemWatcher — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:45, 26 мая 2010
On file created or deleted
using System;
using System.IO;
using System.Windows.Forms;
class MainClass {
static void Main(string[] args) {
using (FileSystemWatcher watch = new FileSystemWatcher()) {
watch.Path = Application.StartupPath;
watch.Filter = "*.*";
watch.IncludeSubdirectories = true;
// Attach the event handler.
watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);
watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);
watch.EnableRaisingEvents = true;
Console.WriteLine("Press Enter to create a file.");
Console.ReadLine();
if (File.Exists("test.bin")) {
File.Delete("test.bin");
}
// Create test.bin.
using (FileStream fs = new FileStream("test.bin", FileMode.Create)) {
// Do something.
}
Console.WriteLine("Press Enter to terminate the application.");
Console.ReadLine();
}
}
private static void OnCreatedOrDeleted(object sender, FileSystemEventArgs e) {
Console.WriteLine("\tNOTIFICATION: " + e.FullPath + "" was " + e.ChangeType.ToString());
Console.WriteLine();
}
}
Set NotifyFilter of FileSystemWatcher
using System;
using System.IO;
public class Program {
static void Main(string[] args) {
FileSystemWatcher watcher = new FileSystemWatcher();
try {
watcher.Path = @"C:\MyFolder";
} catch (ArgumentException ex) {
Console.WriteLine(ex.Message);
return;
}
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.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);
}
}