要求:開機即可進行對於檔案夾進行偵測是否有建立檔案(方法:使用windowsService 和 fileSystemWatcher 監控檔案夾)
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