【问题标题】:File watcher in windows serviceWindows 服务中的文件观察器
【发布时间】:2015-12-17 14:57:15
【问题描述】:

我是初学者,正在尝试开发一种 Windows 服务,该服务会不断检查文件夹(或文件夹组)中是否有任何新文件或更改的文件。一旦检测到任何新文件或更改(文件或文件夹),它就会复制文件(和任何新文件夹)并将其粘贴到另一个位置。

我对 Windows 窗体应用程序做了同样的事情,但在 Windows 服务中我不知道该怎么做 - 我如何在 Windows 服务中做到这一点?

【问题讨论】:

  • 对你有好处,听起来很棒。
  • oki,所以我们知道您正在开发服务,您能否编辑问题并让我们知道您在哪里遇到困难以及是否可以发布一些代码示例。谢谢
  • 你试过 FileSystemWatcher 类吗? msdn.microsoft.com/en-us/library/…

标签: c# vb.net windows-services


【解决方案1】:

您可以使用FileSystemWatcher 类。

【讨论】:

    【解决方案2】:

    以下是我们如何使用不带计时器的文件观察器来完成此任务

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

    【讨论】:

      【解决方案3】:

      这是这个问题的正确答案

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

      在固定的时间间隔后需要轮询来观察文件....这段代码是观察文件 2sec

      protected override void OnStart(string[] args)
      {
          timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
          timer.Interval = 2000;
          timer.Enabled = true; 
          MyMethod();
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      相关资源
      最近更新 更多