Introduction System.IO.FileSystemWatcher Class
Welcome to this installment of the .NET Nuts & Bolts column. In this article we’re going to tackle a task that I’ve run in to a number of times as part of an application that has a number of integration points or data partners. We’re going to build an application that will watch for new files to be created in a specific directory using the System.IO.FileSystemWatcher
class. Once a file has been created, the watcher application will use a WebClient
to transfer the file to an FTP site of our choosing.
Watching for Files
The .NET Framework includes the System.IO.FileSystemWatcher
class to listen for operating system events indicating there are file and/or directory changes. It can be used to monitor when a file is added, deleted, updated, or even renamed. It relies on the implementation of event handlers to decide how each of the scenarios gets handled. There are a number of software products that can do this as well, but this example will let you tailor your own version.
using System; using System.Text; using System.Net; class Program { static string directoryToWatch = ""; static string archiveDirectory = ""; static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Useage: ConsoleApplication2 [WatchDir] [ArchiveDir]"); return; } else { // Make sure the directory location exists if (!System.IO.Directory.Exists(args[0])) { Console.WriteLine("Monitoring dir '{0}' does not exist.", args[0]); return; } else if (!System.IO.Directory.Exists(args[1])) { Console.WriteLine("Archive dir '{0}' does not exist.", args[1]); return; } directoryToWatch = args[0]; archiveDirectory = args[1]; } System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(); watcher.Path = directoryToWatch; // Control the type of events and look for any file watcher.NotifyFilter = System.IO.NotifyFilters.Size|System.IO.NotifyFilters.FileName| System.IO.NotifyFilters.DirectoryName|System.IO.NotifyFilters.CreationTime; watcher.Filter = "*.*"; // Register the event handlers watcher.Changed += new System.IO.FileSystemEventHandler(watcher_Changed); watcher.Created += new System.IO.FileSystemEventHandler(watcher_Created); watcher.Deleted += new System.IO.FileSystemEventHandler(watcher_Changed); watcher.Renamed += new System.IO.RenamedEventHandler(watcher_Renamed); watcher.EnableRaisingEvents = true; while (true) { System.Threading.Thread.Sleep(1000); } } static void watcher_Changed(object sender, System.IO.FileSystemEventArgs e) { } static void watcher_Created(object sender, System.IO.FileSystemEventArgs e) { } static void watcher_Renamed(object sender, System.IO.RenamedEventArgs e) { } }
Use FTP to Upload a File
FTP is a standards based means of transferring files from one location to another. It has been around as a mainstay for moving files across the Internet for quite some time. Microsoft .NET supports FTP with the out of the box implementation of WebClient
. When the WebClient
sees ftp://
as part of the address it will internally use an FtpWebRequest
object to perform the transfer. The following example code demonstrates how to use the WebClient
to upload a file to an FTP site.
static bool FtpFile(string filename) { string host = @"ftp://[YourFtpServerHere]/"; string userName = "[username]"; string password = "[password]"; if (!host.StartsWith("ftp://")) { host = "ftp://" + host; } Uri uri = new Uri(host); System.IO.FileInfo file = new System.IO.FileInfo(filename); string destinationFilename = host + "/" + file.Name; try { WebClient client = new WebClient(); client.Credentials = new NetworkCredential(userName, password); byte[] response = client.UploadFile(destinationFilename, filename); if (response.Length > 0) { Console.WriteLine("Response from upload: {0}", Encoding.ASCII.GetString(response)); } return true; } catch (WebException webEx) { Console.WriteLine("An exception has occurred during the upload: {0}", webEx.Message); return false; } }
With the introduction of the FTP method, we now need to refactor our event handler for catching the file created event in order to use it. The following sample code represents a simple implementation that takes the newly created file, uploads it, and then moves it to an archive folder previously verified to exist.
static void watcher_Created(object sender, System.IO.FileSystemEventArgs e) { // FTP the file FtpFile(e.FullPath); // Move the file to the archive folder System.IO.File.Move(e.FullPath, archiveDirectory + @"" + e.Name); }
Summary
We have examined how to use the System.IO.FileSystemWatcher
to monitor for file system change events raised by the operating system. We combined that with an FTP upload process to allow us to watch for a new file to be dumped in a monitored location, the file is uploaded to an FTP site, and then moved to an archive folder.
Future Columns
The topic of the next column is yet to be determined. If you have something else in particular that you would like to see explained here you could reach me at mark.strawmyer@crowehorwath.com.