.NET Framework: Monitor a Directory for a New File and Use FTP Upload to Copy It

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]");
      	// Make sure the directory location exists
         if (!System.IO.Directory.Exists(args[0]))
           Console.WriteLine("Monitoring dir '{0}' does not exist.", args[0]);
         else if (!System.IO.Directory.Exists(args[1]))
           Console.WriteLine("Archive dir '{0}' does not exist.", args[1]);
         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| 
      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)
    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;
      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 
    // Move the file to the archive folder
    System.IO.File.Move(e.FullPath, archiveDirectory + @"\" + e.Name);


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.

Related Articles

About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds