Many times your code has to monitor changes made to the file system for new or modified files in order to perform certain operations. For example, you may have a notification service that monitors a particular folder for new images added to that directory. Another way to put this question can be: How can you notify users (subscribers) when a particular txt file has been updated in a particular directory?
.NET provides a FileSystemWatcher object defined in the System.IO namespace. let’s review a function that will enable you to monitor a directory for changes.
using System;
using System.IO;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// enable watching
DirectoryWatcher(@"C:\Windows");
// again, stupid code to just keep the function alive
while (true) { Thread.Sleep(1000); }
}
public static void DirectoryWatcher(string directoryToWatch)
{
// check incoming arguments
if (string.IsNullOrWhiteSpace(directoryToWatch))
throw new ArgumentNullException("directoryToWatch");
// create a new FileSystemWatcher
FileSystemWatcher w = new FileSystemWatcher();
// set the directory to watch
w.Path = directoryToWatch;
//this is the heart - setup multiple filters
// to watch various types of changes to watch
w.NotifyFilter = NotifyFilters.Size |
NotifyFilters.FileName |
NotifyFilters.DirectoryName |
NotifyFilters.CreationTime;
// setup which file types do we want to monitor
w.Filter = "*.*";
// setup event handlers to watch for changes
w.Changed += watcher_Change;
w.Created += watcher_Change;
w.Deleted += watcher_Change;
w.Renamed += new RenamedEventHandler(watcher_Renamed);
// just some debugging
Console.WriteLine(
"Manipulate files in {0} to see activity...", directoryToWatch);
// enable watching by allowing events to be raised
w.EnableRaisingEvents = true;
}
static void watcher_Change(object sender,
FileSystemEventArgs e)
{
Console.WriteLine("{0} changed ({1})", e.Name, e.ChangeType);
}
static void watcher_Renamed(object sender,
RenamedEventArgs e)
{
Console.WriteLine("{0} renamed to {1}", e.OldName, e.Name);
}
}
}
This is a very basic example on how to use the file system watcher. The key elements you should note and read more about are the NotifyFilter, Filter and the different notification events (Changed, Created, Deleted, Renamed, etc.).
A couple of questions.
ReplyDeleteWhat drives the FileSystemWatcher? Is it the local machine or can a domain also use this?
Does it work on a local directory only or does it also work across a network? Will my program running locally be able to detect changes across and network?
Thanks
-adam
Yes, a FileSystemWatcher can be used to watch files on a local computer, a network drive or a remote computer. Of course, the account running the program needs to have access to the remote systems.
ReplyDeleteIts, really great.
ReplyDelete
ReplyDeleteEntretenido juego del estilo pares de animales en el que vas a
deber formar conjuntos de por lo menos 3 mascotas
juntas. Tas Murah Admiring the effort and time you put into your site and in depth information you present.
Souvenir Pernikahan Unik dan Undangan Murah di Jogja It’s good to come across a blog every every now and then that isn’t the same old rehashed information.
Souvenir Pernikahan Unik dan Undangan Murah di Jogja Fantastic post! Souvenir Pernikahan Unik dan Undangan Murah di Jogja
I’ve bookmarked your website as well as I’m adding your RSS feeds to my Google account. Souvenir Pernikahan Unik dan Undangan Murah di Jogja se efectuaron en el año 776 Estos últimos son una de las razones por las cuales Farmerama es el favorito de los juegos de animales para sus
usuarios.
This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
ReplyDeletebest budget ultrawide monitor
Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, 4kcomputermonitor.com
ReplyDeleteThe LCD monitor is one of the most fragile and expensive parts of the computer, thus, it pays to handle it with care.4k vs 144hz: What's the best
ReplyDeleteHence it is better you have to affiliated understand when setting up. It is easy to put up a lot better apply for right away. http://gecey.com/24-inch-tv/
ReplyDeleteI recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. Best 240HZ Monitor:[G-Sync, FreeSync, Budget] 2019 Updated
ReplyDeleteHey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. Map network drive
ReplyDeleteGreat Blog to read, It gives more useful information. Thank lot.
ReplyDeleteBest Apache Spark Online Course
Apache Spark and Scala Online Training
Mua vé liên hệ đại lý Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ Vietnam Airline
vé máy bay từ mỹ về việt nam mùa dịch
bay từ đức về việt nam mấy tiếng
vé máy bay từ nhật về việt nam
Aivivu - đại lý chuyên vé máy bay trong nước và quốc tế
ReplyDeleteVé máy bay đi Mỹ
chuyến bay từ mỹ về việt nam
vé máy bay từ frankfurt đi hà nội
lịch bay hà nội moscow
các chuyến bay từ anh về việt nam
các chuyến bay từ châu âu về việt nam
khách sạn cách ly ở hà nội
Clients across the globe hire Python/Django development companies to build their software from scratch. Python companies are multifunctional because of the programming language they use. Python allows developers to build and maintain scalable systems. It's a mature language that can cover all functionality and automate many tasks that developers otherwise have to do by hand. os.path.join
ReplyDeleteGreat! We will be connecting to this enormous post on our site. Continue the good writing.
ReplyDeletebrand strategy SF