如何使用Windows Service c#将文件从一个文件夹复制到另一个文件夹
本文关键字:文件夹 一个 复制 另一个 Service Windows 何使用 文件 | 更新日期: 2023-09-27 18:05:11
如何使用Windows Service c#将文件从一个文件夹复制到另一个文件夹
我尝试这段代码复制文件每30秒,但时间循环是好的,所以复制不能完成。所以我使用Visual Studio 2012。我将安装Windows服务与命令行。如何修复这段代码
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.IO;
using TestWindowService;
namespace TestCopy
{
public partial class Copy : ServiceBase
{
private FileSystemWatcher watcher;
private System.Timers.Timer timer1 = null;
public Copy()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//File.Copy(@"C:'input'*.*", @"D:'output'*.*");
Library.WriteErrorLog("Test window service started");
timer1 = new System.Timers.Timer();
this.timer1.Interval = 30000; //every 30 secs
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
watcher = new FileSystemWatcher();
watcher.Path = "C:''INPUT''";
watcher.Filter = "*.*";
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
String output_dir = "D:''OUTPUT''";
String output_file = Path.Combine(output_dir, e.Name);
File.Copy(e.FullPath, output_file);
// File.Copy() works here
Library.WriteErrorLog("File copy success");
}
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
watcher.Created += new FileSystemEventHandler(OnCreated);
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("Test window service stopped");
}
}
}
每30秒向FileSystemWatcher.Created
添加处理程序。
如果我理解正确的话,您需要每30秒复制一次。
using System;
using System.Collections.Concurrent;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using TestWindowService;
namespace TestCopy
{
public partial class Copy : ServiceBase
{
private FileSystemWatcher watcher;
private System.Timers.Timer timer;
private ConcurrentQueue<FileInfo> lastCreated;
public Copy()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Interval = 30000; //every 30 secs
timer.Elapsed += (s, e) => CopyFiles();
watcher = new FileSystemWatcher();
watcher.Path = "C:''INPUT''";
watcher.Filter = "*.*";
//schedule the file for copying on the next tick
watcher.Created += (s, e) => lastCreated.Enqueue(new FileInfo(e.FullPath));
}
protected override void OnStart(string[] args)
{
timer.Enabled = true;
watcher.EnableRaisingEvents = true;
Library.WriteErrorLog("Test window service started");
}
private void CopyFiles()
{
String output_dir = "D:''OUTPUT''";
FileInfo fi;
while (lastCreated.TryDequeue(out fi))
if (fi.Exists)
fi.CopyTo(Path.Combine(output_dir, fi.Name));
Library.WriteErrorLog("File copy success");
}
protected override void OnStop()
{
watcher.EnableRaisingEvents = false;
timer.Enabled = false;
//empty the queue
FileInfo fi;
while (!lastCreated.IsEmpty)
lastCreated.TryDequeue(out fi);
Library.WriteErrorLog("Test window service stopped");
}
}
}