TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# FileSystemWatcher Tutorial (Changed, e.Name)

Use the FileSystemWatcher class. Specify the Changed event handler to monitor for file changes.
FileSystemWatcher. This class monitors a directory for changes. A program may need to process new files (often written to the directory by other programs).
Many features. FileSystemWatcher provides a way to monitor a directory for file changes, creations, deletions and renames. We do not need Windows Forms to use it.
A console program. This program uses a FileSystemWatcher static field. We initialize it with the new keyword in Init(). We add its Changed event handler.

Changed: This is triggered when a file in the directory is changed. It may execute twice per edit.

Note: To prevent duplicate work, it is a good idea to use a flag bool to indicate what happened—so we just set "needs update" to true.

C# program that uses FileSystemWatcher using System; using System.IO; class Program { static void Main() { Console.WriteLine("MAIN"); Init(); // Run an infinite loop. while (true) { Console.WriteLine("TYPE SOMETHING"); string line = Console.ReadLine(); Console.WriteLine("TYPED: " + line); } } /// <summary> /// Watcher. /// </summary> static FileSystemWatcher _watcher; /// <summary> /// Init. /// </summary> static void Init() { Console.WriteLine("INIT"); string directory = @"C:\programs\"; Program._watcher = new FileSystemWatcher(directory); Program._watcher.Changed += new FileSystemEventHandler(Program._watcher_Changed); Program._watcher.EnableRaisingEvents = true; Program._watcher.IncludeSubdirectories = true; } /// <summary> /// Handler. /// </summary> static void _watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("CHANGED, NAME: " + e.Name); Console.WriteLine("CHANGED, FULLPATH: " + e.FullPath); // Can change program state (set invalid state) in this method. // ... Better to use insensitive compares for file names. } } Output MAIN INIT TYPE SOMETHING test TYPED: test TYPE SOMETHING CHANGED, NAME: file.txt CHANGED, FULLPATH: C:\programs\file.txt CHANGED, NAME: file.txt CHANGED, FULLPATH: C:\programs\file.txt hello TYPED: hello TYPE SOMETHING CHANGED, NAME: file.txt CHANGED, FULLPATH: C:\programs\file.txt CHANGED, NAME: file.txt CHANGED, FULLPATH: C:\programs\file.txt Contents, file.txt, part 1: HELLO WORLD! Contents, file.txt, part 2: HELLO WORLD! X2 Contents, file.txt, part 3: HELLO WORLD! X2 X3
Windows Forms tutorial. Before you can write any code, you must set up your Windows Forms program properly. Open the Toolbox and double-click on the FileSystemWatcher icon.

Then: In the bottom tray, select Properties on the fileSystemWatcher1 label. You can specify the directory you want to monitor for changes.

Example: We use a directory named C:\watch. Next in the Properties panel, click on the lightning bolt and add 4 event handlers.

Info: Once the program is run, you can change files in the C:\watch directory and dialog boxes will display the events.

MessageBox
C# program that uses FileSystemWatcher, Windows Forms using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e) { // Occurs when the contents of the file change. MessageBox.Show(string.Format("Changed: {0} {1}", e.FullPath, e.ChangeType)); } void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e) { // FullPath is the new file's path. MessageBox.Show(string.Format("Created: {0} {1}", e.FullPath, e.ChangeType)); } void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e) { // FullPath is the location of where the file used to be. MessageBox.Show(string.Format("Deleted: {0} {1}", e.FullPath, e.ChangeType)); } void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e) { // FullPath is the new file name. MessageBox.Show(string.Format("Renamed: {0} {1}", e.FullPath, e.ChangeType)); } } }
A problem. You may have a problem with receiving multiple Changed events for a single file change. This must be due to a technical detail about how some programs write files.

Note: You may need special code to filter Changed events. This depends on your application.

Timer. One of my favorite techniques for monitoring a program for changes is using a Timer instance and simply doing a scan on a regular interval.

And: In this way, you could simply scan a directory every five seconds for changes.

Also: You can then call methods based on the changed detected. You could use the FileInfo type as well as the Timer type for this.

TimerFileInfoFileInfo Length
A summary. We examined the FileSystemWatcher class. This type presents an excellent way to persistently monitor a directory for changes, without lots of custom code.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf