我試圖創建一個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