Skip to main content
 首页 » 编程设计

c#之Windows Service中如何实现文件处理

2024年02月23日11yxwkf

如何为多个目录创建监视 Windows 服务 (C#) 以扫描新文件并(如果有)编辑、重命名、将它们移动到其他位置?我已经创建了一个 WorkerTask() 但它只适用于我启动服务时目录中的文件,不适用于我稍后放在那里的文件。它必须 24/7 全天候运行。

private void WorkerTask() { 
    while (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); 
        } 
      } 
    } 
} 

我如何不断扫描上传到此文件夹的新(仅完整!)文件?它必须在两次扫描之间最多延迟 2-3 秒运行,以便文件一进入文件夹就会被处理和移动。我见过 FileSystemWatcher() 但我认为尝试为多个输入文件夹实现它可能不是一个好主意。

请您参考如下方法:

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. 
}