开发者

How to implement file processing in Windows Service?

How do I create a monitoring Windows Service (C#) for several directories to scan for new files and (if there are any) edit, rename, move them somewhere else? I have created a WorkerTask() but it works only for files that are in directory when I start the service, not for the ones I put there later. It has to run 24/7.

private void WorkerTask() {
    whi开发者_开发百科le (running) {
    // only 1 input dir in this case
    string[] filePaths = Directory.GetFiles(input_dir, "*.jpg");
      if (filePaths.Lenght > 0)
      {
        foreach (String file_path in filePaths)
        {
            // some other operations before moving
            File.Move(file_path, output_file_path);
        }
      }
    }
}

How can I constantly scan for new (only complete!) files that are being uploaded to this folder? It has to run with like a maximum of 2-3 seconds delay between scans, so that as soon as the file lands in folder it's processed and moved. I've seen FileSystemWatcher() but I think trying to implement it for multiple input folders might not be a good idea.


public void Start()
{
    FileSystemWatcher fsw = new FileSystemWatcher();
    fsw.Path = "\\server\share";  //or use your inputdir
    fsw.NotifyFilter = NotifyFilters.Size;  //(several others available)
    fsw.Filter = "*.jpg";
    fsw.Changed += new FileSystemEventHandler(OnChanged);
    fsw.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
    //do stuff.
}


Use the FileSystemWatcher class, that's what it's for.

It has several events that you can subscribe for - when files are created, updated and deleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜