我试图创建一个Windows服务,将抓住新文件上传到目录,编辑它们并移动到其他目录。看来我可以复制它们,但不能移动。这是为什么?目录扫描仪Windows服务与FileSystemWatcher
using System;
using System.ServiceProcess;
using System.Threading;
using System.IO;
namespace ImportService
{
public class ImportServer : ServiceBase
{
private System.Diagnostics.EventLog eventLog1;
private FileSystemWatcher watcher;
public ImportServer()
{
this.ServiceName = "ImportService";
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("ImportServiceLogSource"))
System.Diagnostics.EventLog.CreateEventSource("ImportServiceLogSource", "ImportServiceLog");
eventLog1.Source = "ImportServiceLogSource";
eventLog1.Log = "ImportServiceLog";
}
public static void Main()
{
ServiceBase.Run(new ImportServer());
}
protected override void OnStart(string[] args)
{
//base.OnStart(args);
eventLog1.WriteEntry("service started");
watcher = new FileSystemWatcher();
watcher.Path = "C:\\INPUT\\";
watcher.Filter = "*.jpg";
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler(OnCreated);
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
String output_dir = "C:\\OUTPUT\\";
String output_file = Path.Combine(output_dir, e.Name);
File.Move(e.FullPath, output_file);
// File.Copy() works here
eventLog1.WriteEntry("moving file to " + output_file);
}
protected override void OnStop()
{
eventLog1.WriteEntry("service stopped");
base.OnStop();
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnPause()
{
base.OnPause();
}
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
}
}
我也应该保留base.OnStart();
等。它真的做什么?
更新:如何移动在观察目录中创建的文件? 文件已在使用异常问题。
好的,找出了自动启动解决方案。 File.Move()导致一个问题(服务仅检测到第一个创建/复制的文件,然后崩溃),但仍在处理它。 – yosh 2011-05-05 11:01:46
File.Move(...)抛出什么异常?此外,base.OnStart()可确保运行ServiceBase的OnStart方法中的任何内容。如果没有什么,你不需要叫它。 – 2011-05-05 11:31:15
“文件无法移动,因为它被另一个进程使用”。什么样的条件/计时器会尽快移动文件? – yosh 2011-05-05 11:50:52