Monitoring a directory for new file creation without FileSystemWatcher

前端 未结 8 543
臣服心动
臣服心动 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:27

    It is a little odd that you cannot use FileSystemWatcher or presumably any of the Win32 APIs that do the same thing, but that is irrelevant at this point. The polling method might look like this.

    public class WorseFileSystemWatcher : IDisposable
    {
      private ManaulResetEvent m_Stop = new ManaulResetEvent(false);
    
      public event EventHandler Change;
    
      public WorseFileSystemWatcher(TimeSpan pollingInterval)
      {
        var thread = new Thread(
          () =>
          {
            while (!m_Stop.WaitOne(pollingInterval))
            {
              // Add your code to check for changes here.
              if (/* change detected */)
              {
                if (Change != null)
                {
                  Change(this, new EventArgs())
                }
              }
            }
          });
        thread.Start();
      }
    
      public void Dispose()
      {
        m_Stop.Set();
      }
    }
    
    0 讨论(0)
  • 2021-01-31 07:28

    At program startup, use Directory.GetFiles(path) to get the list of files.

    Then create a timer, and in its elapsed event call hasNewFiles:

        static List<string> hasNewFiles(string path, List<string> lastKnownFiles)
        {
            List<string> files = Directory.GetFiles(path).ToList();
            List<string> newFiles = new List<string>();
    
            foreach (string s in files)
            {
                if (!lastKnownFiles.Contains(s))
                    newFiles.Add(s);
            }
    
            return new List<string>();
        }
    

    In the calling code, you'll have new files if:

        List<string> newFiles = hasNewFiles(path, lastKnownFiles);
        if (newFiles.Count > 0)
        {
            processFiles(newFiles);
            lastKnownFiles = newFiles;
        }
    

    edit: if you want a more linqy solution:

        static IEnumerable<string> hasNewFiles(string path, List<string> lastKnownFiles)
        {
            return from f in Directory.GetFiles(path) 
                   where !lastKnownFiles.Contains(f) 
                   select f;
        }
    
        List<string> newFiles = hasNewFiles(path, lastKnownFiles); 
        if (newFiles.Count() > 0) 
        { 
            processFiles(newFiles); 
            lastKnownFiles = newFiles; 
        } 
    
    0 讨论(0)
提交回复
热议问题