Search code examples
c#vb.netwindows-services

File watcher in windows service


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?


Solution

  • 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();
    }