1.從WindowsService 說起,新建一個windowService 文件,命名爲:LogTransferService.cs
2.拖入一個FileSystemWatcher 命名爲 fileSystemWatcher1 :偵聽文件系統更改通知,並在目錄或目錄中的文件發生更改時引發事件。
3. 通過一個方法設置偵聽的文件夾,對文件夾操作的方式,偵聽文件的類型.........
//<summary>
//使用FileSystemWatcher:偵聽文件系統創建通知,並在文件發生更改的時候引發事件。
//</summary>
private void UsingFileSystemWatcher()
{
string watcherFilePath = "E://POS_WS//POS_LogTransferService//POS_LogTransferService//UpdateLog";
//設置偵聽目錄
fileSystemWatcher1.Path = watcherFilePath;
fileSystemWatcher1.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess;
fileSystemWatcher1.Filter = "*.txt";
//是否監視子目錄
fileSystemWatcher1.IncludeSubdirectories = false;
#region 觸發的事件(文件創建的時候觸發事件 4 )
fileSystemWatcher1.Created +=new FileSystemEventHandler(fileSystemWatcher1_Created);
#endregion
}
4. #region 觸發事件的方法
/// <summary>
/// 文件創建的時候觸發
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
TransferType transferType = new TransferType();
//獲得後綴
string suffix = e.Name.Substring(e.Name.LastIndexOf('.')+1, e.Name.Length - e.Name.LastIndexOf('.')-1);
string fileName = fileSystemWatcher1.Path + "//" + e.Name;
if (suffix == "txt")
transferType = TransferType.TextFileTransfer;
Transfer(fileName, transferType);
}
#endregion
5. 在服務啓動時候進行檢測:
/// <summary>
/// 服務啟動
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
//使用FileSystemWatcher:偵聽文件系統
UsingFileSystemWatcher();
//服務開啟的時候,發送郵件通知
SendMsgAboutServer(MsgSenderType.EmailSender, TransferService.ServerStart);
}
6. 安裝與卸載服務
在windowsService 頁面 右鍵 加入安裝程式自動生成 ServcieProcessInstall1 和ServiceInstaller 兩個
通過ServiceProcessInstall 可以進行設置 訪問的方式:Account:LocalService,NetWorkService,LoaclSystem,User
通過ServiceInstaller可以設置 DispalyName(安裝服務後的顯示名稱),ServiceName,StartType(服務啓動方式:自動或者手動)
7.生成解決方案:在該項目的debug 文件夾下面會有 生成服務的.exe 文件
安裝該文件的命令:從Visual studio tools-->進入命令提示符--->進入生成的.exe路徑
安裝:輸入命令: instalutil POS_LogTransferService.exe
卸載:輸入命令:installutil /u POS_LogTransferService.exe