2

I am beginner trying to develop a Windows service which keeps checking a folder (or group of folders) for any new file or changed files. As soon as it detects any new file or changes (to files or folders) then it copies the files (and any new folders) and paste it to another location.

I have done the same thing with a Windows Forms application but in a Windows Service I don't know what to do - how can I do this in a Windows Service?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Vikash Pandey
  • 4,037
  • 3
  • 16
  • 8
  • 6
    Good for you, sounds great. – Tim Lloyd Nov 16 '11 at 08:33
  • 4
    oki so we understand that you're developing the service, could you edit the question and let us know where you encountered dificulties and if you can post some code examples . thanks – Poelinca Dorin Nov 16 '11 at 08:33
  • Have you tried the FileSystemWatcher class? http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx#Y0 – kol Nov 16 '11 at 08:35

3 Answers3

7

You could use the FileSystemWatcher class.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Here is how we can complete this task using file watcher without timer

public void ProcessFile(string filepath)
    {
        var fileN ="newfilename";
        string destfile = "E:\\2nd folder" + fileN;
        File.Copy(filepath, destfile, true);
    }

    protected override void OnStart(string[] args)
    {
       String[] files = Directory.GetFiles("E:\\", "*.*");
        foreach (string file in files)
        {
            ProcessFile(file);
        }
        var fw = new FileSystemWatcher("folderpath");
        fw.IncludeSubdirectories = false;
        fw.EnableRaisingEvents = true;
        fw.Created += Newfileevent;

    }
    static void Newfileevent(object sender, FileSystemEventArgs e)
    {
        ProcessFile(e.FullPath);

    }
Narendra
  • 1,332
  • 2
  • 13
  • 16
-4

Here is correct answer for this question

public static void MyMethod()
{
    String[] files = Directory.GetFiles("E:\\", "*.*");
    foreach (string file in files)
    {
        var fileN = file.Substring(2);
        string destfile = "E:\\2nd folder" + fileN;
        File.Copy(file, destfile, true);
    }
}

polling is needed to watch the file after a fix interval of time....this code is watch the file 2sec

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 2000;
    timer.Enabled = true; 
    MyMethod();
}
Justin
  • 84,773
  • 49
  • 224
  • 367
Vikash Pandey
  • 4,037
  • 3
  • 16
  • 8