Monitor a Directory for a New File

Watching for Files


The .NET Framework includes the System.IO.FileSystemWatcher class to listen for operating system events indicating there are file 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. This example will let you try your own version.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWatcher
{
    class Program
    {
        static string directoryPath = @"C:\MyDir\";
        static void Main(string[] args)
        {
            if (args.Length > 2)
            {
                Console.WriteLine("Useage: ConsoleApplication2 [WatchDir] [ArchiveDir]");
                return;
            }
            else
            {
                // Make sure the directory location exists
                if (!Directory.Exists(directoryPath))
                {
                    Console.WriteLine("The directory '{0}' does not exist.", directoryPath);
                    return;
                }
            }
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = directoryPath;
            // Specifying the filter types
            watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
            watcher.Filter = "*.*";
            // Register the event handlers
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
            watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
            // Enables the events
            watcher.EnableRaisingEvents = true;
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
            }
        }
        /// <summary>
        /// Handles the Changed event of the watcher control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.IO.FileSystemEventArgs"/> instance containing the event data.</param>
        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("The file {0} has been changed", e.Name);
        }
        /// <summary>
        /// Handles the Created event of the watcher control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.IO.FileSystemEventArgs"/> instance containing the event data.</param>
        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("A new file {0} is created", e.Name);
        }
        /// <summary>
        /// Handles the Renamed event of the watcher control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.IO.RenamedEventArgs"/> instance containing the event data.</param>
        static void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("The file {0} has been renamed", e.Name);
        }
    }
}

Use FTP to Upload a File


FTP is a standards based means of transferring files from one location to another. It has been there 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 UploadFile(string filename)
  {
    string host = @"ftp://[YourFtpServerHere]/";
    string userName = "[username]";
    string password = "[password]";
   
    // Checks for the URL starts from ftp://..
    if (!host.StartsWith("ftp://"))
    {
      host = "ftp://" + host;
    }
 
    Uri uri = new Uri(host);
    FileInfo file = new FileInfo(filename);
    string destinationFilename = host + "/" + file.Name;
 
    try
    {
      WebClient client = new WebClient();
      // Setting the User Credentials
      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 occurred during the upload: {0}", webEx.Message);
      return false;
    }
  }

With modifing the static void watcher_Created(object sender, FileSystemEventArgs e) event, with

 
static void watcher_Created(object sender, FileSystemEventArgs e)
{
         UploadFile(e.Name);
}
Ebook Download
View all
Learn
View all