我正在学习.net并按照以下教程http://www.beansoftware.com/NET-Tutorials/Create-Windows-Services.aspx
编写服务Windows服务已成功安装并且也会启动。但是当我更改文件名或删除文件或添加文件时,它不会将任何信息添加到我的日志文件中 C:\文件夹\ FolderLog.txt
我看到了FolderWatcher_ * *的3种方法,但我没有看到代码中的那些方法。我对.net很新,所以我不确定他们是如何被称为
这是我的完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace Watcher
{
public partial class Watcher : ServiceBase
{
public Watcher()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
writer.Close();
}
private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
writer.Close();
}
private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
writer.Close();
}
}
}
我已经完成了该教程中的每一步。我没有看到任何描述如何调用这些方法的东西。任何帮助都会很棒
答案 0 :(得分:3)
本教程可能会在您的服务的设计模式表面添加FileSystemWatcher
。在设计模式下,选择该对象,并在其事件处理程序中,选择类的相应方法。
答案 1 :(得分:1)
确保将观察程序实例“FolderWatcher
”的事件注册到代码中的事件处理程序,您可以在服务设计者或服务的构造函数中执行此操作,例如:
public Watcher()
{
InitializeComponent();
FolderWatcher.Created += FolderWatcher_Created;//when created FolderWatcher_Created will be called
FolderWatcher.Deleted += FolderWatcher_Deleted;//when deleted call FolderWatcher_Deleted will be called
FolderWatcher.Renamed += FolderWatcher_Renamed;//when renamed FolderWatcher_Renamed will be called
}