Creating a hot folder window service using FileSystemWatcher.

Many times we need to a utility that can watch the specified folder(s) contents and can take actions accordingly.

For example we can share a directory namely "Music" on our machine. Anyone can put the music files to this folder, as soon as a music file comes to this folder, the music file is copied to the user's favorite music folder.

For this task to do we need to develop a window service. This window service will continuously watch the shared music folder with the help of

FileSystemWatcher

.

Beolw is the code to achieve the same.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;

namespace FolderPollerService
{
public partial class FolderPollerSrvc : ServiceBase
{
FileSystemWatcher[] watchers;
public FolderPollerSrvc()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
// get the list of hot folders, let say from registry.
string[] sFolders = //get the folder's path
if (sFolders != null && sFolders .Length > 0)
{
watchers = new FileSystemWatcher[hotfolderInfo.Length];
for (int i = 0; i < hotfolderInfo.Length; i++)
{
watchers[i] = new FileSystemWatcher();
watchers[i].Path = sFolders [i];
watchers[i].NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watchers[i].Filter = "*.mp3";
watchers[i].EnableRaisingEvents = true;
watchers[i].Created += new FileSystemEventHandler(FSWatcher_Created);
}
}
}

void FSWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
//put the file to user's favorite music folder
}

protected override void OnStop()
{
}
}
}


Comments

Author: Ben Letto01 Jan 2009 Member Level: Bronze   Points : 1

Hello Shobhit,
I'm interested in using this code...but it is not compiling for me. It has a problem with:

1) "InitializeComponent" does not exist in current context
2) "hotfolderInfo", it does not exist in current context

I'm running .NET 2.0

Thanks for your help!
Ben

Author: Tony02 Jul 2012 Member Level: Bronze   Points : 0

I found this via google. I know nothing about .net programming or how to utilize this code. That said I have never seen a Windows hot folder and would greatly appreciate help in getting this to work.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: