3
我有一個windows服務需要監視文件的目錄,然後將其移動到另一個目錄。我正在使用FileSystemWatcher來實現這一點。在Windows服務中使用FileSystemWatcher
這是我的主要服務類。
public partial class SqlProcessService : ServiceBase
{
public SqlProcessService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
FileProcesser fp = new FileProcesser(ConfigurationManager.AppSettings["FromPath"]);
fp.Watch();
}
protected override void OnStop()
{
}
}
這是我FileProcessor類
public class FileProcesser
{
FileSystemWatcher watcher;
string directoryToWatch;
public FileProcesser(string path)
{
this.watcher = new FileSystemWatcher();
this.directoryToWatch = path;
}
public void Watch()
{
watcher.Path = directoryToWatch;
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, ConfigurationManager.AppSettings["ToPath"]+"\\"+Path.GetFileName(e.FullPath),true);
File.Delete(e.FullPath);
}
}
我安裝並啓動服務後,它的工作原理罰款1個文件,然後自動停止。什麼使服務自動停止?當我檢查事件日誌時,我沒有看到錯誤或警告!
您可以將Visual Studio調試器附加到進程並對其進行調試。也可以使用try catch並將異常寫入文本文件。 – dotctor
它崩潰了嗎?做一個嘗試趕上並記錄 –