基於0起步來創建一個服務,做到簡單的記錄時間日志功能,其具體招行方法可自行添加。
1.創建服務
2.刪除默認服務文件
3.添加自己的服務文件
4.更改啟動項目
5. 引用 using System.Timers;並添加FileClass類
FileClass類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace TerminalTrance { public class FileClass { //創建文件夾 //參數:path 文件夾路徑 public bool CreateFolder(string path) { try { if (Directory.Exists(path)) { return true; } if (!Directory.Exists(path.Substring(0, path.LastIndexOf("\\")))) { //若路徑中無“\”則表示路徑錯誤 return false; } else { //創建文件夾 DirectoryInfo dirInfo = Directory.CreateDirectory(path); return true; } } catch (Exception ex) { return false; } } //創建文件 //參數:path 文件路徑 public void CreateFile(string path) { try { if (CreateFolder(path.Substring(0, path.LastIndexOf("\\")))) { if (!File.Exists(path)) { FileStream fs = File.Create(path); fs.Close(); } } } catch (Exception ex) { return; } } //刪除文件 //參數:path 文件夾路徑 public void DeleteFile(string path) { try { if (!File.Exists(path)) { return; } else { File.Delete(path); } } catch (Exception ex) { return; } } //寫文件 //參數:path 文件夾路徑 、content要寫的內容 public void WriteFile(string path, string content) { try { if (!File.Exists(path)) { CreateFile(path); } FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(content); sw.Close(); } catch (Exception ex) { return; } } /// <summary> /// 將即時日志保存入日志文件 /// </summary> public void WriteLogFile(string directoryPath, string content) { if (!Directory.Exists(directoryPath)) { CreateFolder(directoryPath); } try { //寫入新的文件 string filePath = directoryPath + "\\" + DateTime.Now.Date.ToString("yyyyMMdd") + ".log"; FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(content); sw.Close(); fs.Close(); } catch (Exception ex) { } } } }
6. 添加上步中需要的InitService()方法
/// <summary> /// 初始化服務參數 /// </summary> private void InitService() { base.CanShutdown = true; base.CanStop = true; base.CanPauseAndContinue = true; this.ServiceName = MainService.serviceName; this.AutoLog = false;//為了使用自定義日志,必須將 AutoLog 設置為 false tim = new System.Timers.Timer(); tim.Elapsed += new ElapsedEventHandler(tim_Elapsed); tim.Interval = 5000; tim.AutoReset = true; }
7. 解決System不包含windows屬性問題,引用程序集。
8.添加上面引用 的 tim_Elapsed 定時方法
private void tim_Elapsed(object sender, EventArgs e) { StartThread(); } /// <summary> /// 開始任務 /// </summary> private void StartThread() { MessageAdd(serviceName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } /// <summary> /// 日志記錄 /// </summary> /// <param name="serviceName">內容</param> public void MessageAdd(string str) { try { fileclass.WriteLogFile(logPath, str);//寫入記錄日志 } catch { } }
9.此時生成解決方案是成功的
10.在OnStart等中寫入自己的方法,這里用日志記錄
protected override void OnStart(string[] args) { try { this.tim.Enabled = true; this.tim.Start(); } catch (Exception ex) { MessageAdd("OnStart錯誤:" + ex.Message); } MessageAdd(serviceName + "已成功啟動!"); } protected override void OnStop() { try { this.tim.Stop(); } catch (Exception ex) { MessageAdd("OnStop錯誤:" + ex.Message); } MessageAdd(serviceName + "已停止!"); } protected override void OnContinue() { this.tim.Start(); base.OnContinue(); } protected override void OnPause() { this.tim.Stop(); base.OnPause(); }
11.給服務添加安裝程序。右鍵鼠標單擊MainService.cs[設計]*選項卡選項“添加安裝程序”。
12.可以看見項目中多了如下文件和組件,serviceProcessInstaller1、serviceInstaller1是自動生成的
13.設置組件serviceInstaller1的主要屬性,StartType: AutoMatic自動啟動;ServiceName: 服務系統標識,在cmd命令中執行sr start/stop/query等等命令時候使用,用來唯一標識一個Window服務
14.設置組件serviceProcessInstaller1的主要屬性,Accout:賬戶類型,LocalSystem本地系統服務;
15.設置服務安裝后“允許和桌面進行交互”,
需要在ProjectInstaller.cs中添加如下代碼。
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; namespace TerminalTrance { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } protected override void OnAfterInstall(IDictionary savedState) { try { base.OnAfterInstall(savedState); // 允許服務桌面交互 System.Management.ManagementObject myService = new System.Management.ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName)); System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change"); changeMethod["DesktopInteract"] = true; System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null); } catch (Exception ex) { } } } }
16.Windows服務的安裝和卸載
代碼寫完后,編譯通過后,就可以安裝、卸載、調試服務了。
在執行安裝或卸載服務前,我有把服務需要的相關文件,復制到C:\Service\下面或其他路徑。一旦安裝完成后,此目錄不能變更,否則不能卸載該服務和服務運行會報錯。
安裝、卸載很簡單,只要在VS命令行導航到,服務程序的路徑。然后運行以下命令就OK了。
打開如圖:
安裝服務:installutil C:\Service\TerminalTrance.exe
卸載服務:installutil /u C:\Service\TerminalTrance.exe
調試的話,只能先安裝啟動服務,然后將該服務附加到進程,就可以調試了。安裝好服務后,就可以在win7服務管理里面,管理剛剛啟動的服務了。
安裝成功后可在服務中看到
在服務程序中可以看到添加的服務
可以看到程序的日志記錄
另外一個方法是生成安裝exe程序
1.解決方案右鍵=》新建項目=》選擇安裝程序
2.安裝項目右鍵=》添加=》項目輸出,選擇主項目
3.安裝項目右鍵=》視圖=》自定義操作
4.自定義操作=》安裝右鍵=》選擇主輸出
5.卸載右鍵=》選擇主輸出
6.若有文件需要添加到安裝后的文件夾中=》點擊應用程序文件夾=》添加=》文件,選擇文件。安裝后就會生成指定文件。
7.生成程序,完成,Setup文件夾中找到exe安裝文件執行就 OK了。卸載也是執行此exe,按提示下一步就OK。