Monitoring a directory for new file creation without FileSystemWatcher

前端 未结 8 547
臣服心动
臣服心动 2021-01-31 06:51

I have to create a Windows service which monitors a specified folder for new files and processes it and moves it to other location.

I started with using FileSyste

8条回答
  •  生来不讨喜
    2021-01-31 07:08

    Using @Petoj's answer I've included a full windows service that polls every five minutes for new files. Its contrained so only one thread polls, accounts for processing time and supports pause and timely stopping. It also supports easy attaching of a debbugger on system.start

     public partial class Service : ServiceBase{
    
    
        List fileList = new List();
    
        System.Timers.Timer timer;
    
    
        public Service()
        {
            timer = new System.Timers.Timer();
            //When autoreset is True there are reentrancy problems.
            timer.AutoReset = false;
    
            timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
        }
    
    
        private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
        {
           LastChecked = DateTime.Now;
    
           string[] files = System.IO.Directory.GetFiles("c:\\", "*", System.IO.SearchOption.AllDirectories);
    
           foreach (string file in files)
           {
               if (!fileList.Contains(file))
               {
                   fileList.Add(file);
    
                   do_some_processing();
               }
           }
    
    
           TimeSpan ts = DateTime.Now.Subtract(LastChecked);
           TimeSpan MaxWaitTime = TimeSpan.FromMinutes(5);
    
           if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
               timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds;
           else
               timer.Interval = 1;
    
           timer.Start();
        }
    
        protected override void OnPause()
        {
            base.OnPause();
            this.timer.Stop();
        }
    
        protected override void OnContinue()
        {
            base.OnContinue();
            this.timer.Interval = 1;
            this.timer.Start();
        }
    
        protected override void OnStop()
        {
            base.OnStop();
            this.timer.Stop();
        }
    
        protected override void OnStart(string[] args)
        {
           foreach (string arg in args)
           {
               if (arg == "DEBUG_SERVICE")
                       DebugMode();
    
           }
    
            #if DEBUG
                DebugMode();
            #endif
    
            timer.Interval = 1;
            timer.Start();
       }
    
       private static void DebugMode()
       {
           Debugger.Break();
       }
    
     }
    

提交回复
热议问题