C#Windows服務(wù)程序開發(fā)實例介紹
C#Windows服務(wù)程序開發(fā)實例程序的目的和用途:
很多開機(jī)啟動程序僅僅加在啟動項里面,只有登陸后才真正啟動。windows服務(wù)在開機(jī)未進(jìn)行用戶登錄前就啟動了。正是利用這一點,解決一些服務(wù)器自動重啟后特定軟件也自動啟動的問題。
C#Windows服務(wù)程序開發(fā)1.
新建一個服務(wù)項目 visual C#----windows----windows服務(wù);
C#Windows服務(wù)程序開發(fā)2.
添加一個dataset(.xsd),用于存儲啟動目標(biāo)的路徑,日志路徑等。
在dataset可視化編輯中,添加一個datatable,包含兩列 StartAppPath 和 LogFilePath。分別用于存儲目標(biāo)的路徑、日志路徑。
我認(rèn)為利用dataset.xsd存儲配置參數(shù)的優(yōu)勢在于可以忽略xml解析的具體過程直接使用xml文件。
在dataset中 提供了ReadXml方法用于讀取xml文件并將其轉(zhuǎn)換成內(nèi)存中的一張datatable表,數(shù)據(jù)很容易取出來!同樣,WriteXml方法用于存儲為xml格式的文件,也僅僅需要一句話而已。
C#Windows服務(wù)程序開發(fā)3.
program.cs文件 作為程序入口,代碼如下:
- view plaincopy to clipboardprint?
- using System.Collections.Generic;
- using System.ServiceProcess;
- using System.Text;
- namespace WindowsServices_AutoStart
- {
- static class Program
- {
- /// ﹤summary﹥
- /// 應(yīng)用程序的主入口點。
- /// ﹤/summary﹥
- static void Main()
- {
- ServiceBase[] ServicesToRun;
- // 同一進(jìn)程中可以運(yùn)行多個用戶服務(wù)。若要將
- // 另一個服務(wù)添加到此進(jìn)程中,請更改下行以
- // 創(chuàng)建另一個服務(wù)對象。例如,
- //
- // ServicesToRun = new ServiceBase[] {
- new Service1(), new MySecondUserService()};
- //
- ServicesToRun = new ServiceBase[] {
- new WindowsServices_AutoStart() };
- ServiceBase.Run(ServicesToRun);
- }
- }
- }
- using System.Collections.Generic;
- using System.ServiceProcess;
- using System.Text;
- namespace WindowsServices_AutoStart
- {
- static class Program
- {
- /// ﹤summary﹥
- /// 應(yīng)用程序的主入口點。
- /// ﹤/summary﹥
- static void Main()
- {
- ServiceBase[] ServicesToRun;
- // 同一進(jìn)程中可以運(yùn)行多個用戶服務(wù)。若要將
- // 另一個服務(wù)添加到此進(jìn)程中,請更改下行以
- // 創(chuàng)建另一個服務(wù)對象。例如,
- //
- // ServicesToRun = new ServiceBase[] {
- new Service1(), new MySecondUserService()};
- //
- ServicesToRun = new ServiceBase[] {
- new WindowsServices_AutoStart() };
- ServiceBase.Run(ServicesToRun);
- }
- }
- }
C#Windows服務(wù)程序開發(fā)4.
service.cs主文件,代碼如下:
- view plaincopy to clipboardprint?
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.IO;
- using System.Diagnostics;
- using System.ServiceProcess;
- using System.Text;
- namespace WindowsServices_AutoStart
- {
- public partial class
- WindowsServices_AutoStart : ServiceBase
- {
- public WindowsServices_AutoStart()
- {
- InitializeComponent();
- }
- string StartAppPath ="";
- //@"F:\00.exe";
- string LogFilePath ="";
- // @"f:\WindowsService.txt";
- protected override void OnStart(string[] args)
- {
- string exePath = System.Threading.
- Thread.GetDomain().BaseDirectory;
- //
- if (!File.Exists(exePath + @"\ServiceAppPath.xml"))
- {
- dsAppPath ds = new dsAppPath();
- object[] obj=new object[2];
- obj[0]="0";
- obj[1]="0";
- ds.Tables["dtAppPath"].Rows.Add(obj);
- ds.Tables["dtAppPath"].WriteXml(
- exePath + @"\ServiceAppPath.xml");
- return;
- }
- try
- {
- dsAppPath ds = new dsAppPath();
- ds.Tables["dtAppPath"].ReadXml(
- exePath + @"\ServiceAppPath.xml");
- DataTable dt = ds.Tables["dtAppPath"];
- StartAppPath = dt.Rows[0]
- ["StartAppPath"].ToString();
- LogFilePath = dt.Rows[0]
- ["LogFilePath"].ToString();
- }
- catch { return; }
- if (File.Exists(StartAppPath))
- {
- try
- {
- Process proc = new Process();
- proc.StartInfo.FileName = StartAppPath; //注意路徑
- //proc.StartInfo.Arguments = "";
- proc.Start();
- }
- catch (System.Exception ex)
- {
- //MessageBox.Show(this, "找不到幫助文件路徑。
- 文件是否被改動或刪除?\n" + ex.Message, "提示",
- MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- FileStream fs = new FileStream(LogFilePath,
- FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("WindowsService:
- Service Started" + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- }
- protected override void OnStop()
- {
- try
- {
- // TODO: 在此處添加代碼以執(zhí)行停止服務(wù)所需的關(guān)閉操作。
- FileStream fs = new FileStream(LogFilePath,
- FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("WindowsService:
- Service Stopped " + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- catch
- {
- }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.IO;
- using System.Diagnostics;
- using System.ServiceProcess;
- using System.Text;
- namespace WindowsServices_AutoStart
- {
- public partial class
- WindowsServices_AutoStart : ServiceBase
- {
- public WindowsServices_AutoStart()
- {
- InitializeComponent();
- }
- string StartAppPath ="";
- //@"F:\00.exe";
- string LogFilePath ="";
- // @"f:\WindowsService.txt";
- protected override void OnStart(string[] args)
- {
- string exePath = System.
- Threading.Thread.GetDomain().BaseDirectory;
- //
- if (!File.Exists(exePath + @"\ServiceAppPath.xml"))
- {
- dsAppPath ds = new dsAppPath();
- object[] obj=new object[2];
- obj[0]="0";
- obj[1]="0";
- ds.Tables["dtAppPath"].Rows.Add(obj);
- ds.Tables["dtAppPath"].WriteXml(
- exePath + @"\ServiceAppPath.xml");
- return;
- }
- try
- {
- dsAppPath ds = new dsAppPath();
- ds.Tables["dtAppPath"].ReadXml(
- exePath + @"\ServiceAppPath.xml");
- DataTable dt = ds.Tables["dtAppPath"];
- StartAppPath = dt.Rows[0]
- ["StartAppPath"].ToString();
- LogFilePath = dt.Rows[0]
- ["LogFilePath"].ToString();
- }
- catch { return; }
- if (File.Exists(StartAppPath))
- {
- try
- {
- Process proc = new Process();
- proc.StartInfo.FileName = StartAppPath; //注意路徑
- //proc.StartInfo.Arguments = "";
- proc.Start();
- }
- catch (System.Exception ex)
- {
- //MessageBox.Show(this, "
- 找不到幫助文件路徑。文件是否被改動或刪除?\n"
- + ex.Message, "提示", MessageBoxButtons.OK,
- MessageBoxIcon.Information);
- }
- FileStream fs = new FileStream(LogFilePath,
- FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("WindowsService:
- Service Started" + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- }
- protected override void OnStop()
- {
- try
- {
- // TODO: 在此處添加代碼以執(zhí)行停止服務(wù)所需的關(guān)閉操作。
- FileStream fs = new FileStream(LogFilePath,
- FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("WindowsService:
- Service Stopped " + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
- catch
- {
- }
- }
- }
- }
C#Windows服務(wù)程序開發(fā)5.
啟動調(diào)試,成功時也會彈出一個對話框大致意思是提示服務(wù)需要安裝。
C#Windows服務(wù)程序開發(fā)6.
把Debug文件夾下面的.exe執(zhí)行程序,安裝為windows系統(tǒng)服務(wù),安裝方法網(wǎng)上很多介紹。我說一種常用的:
C#Windows服務(wù)程序開發(fā)之安裝服務(wù)
訪問項目中的已編譯可執(zhí)行文件所在的目錄。
用項目的輸出作為參數(shù),從命令行運(yùn)行 InstallUtil.exe。在命令行中輸入下列代碼:
installutil yourproject.exe
C#Windows服務(wù)程序開發(fā)之卸載服務(wù)
用項目的輸出作為參數(shù),從命令行運(yùn)行 InstallUtil.exe。
installutil /u yourproject.exe
至此,整個服務(wù)已經(jīng)編寫,編譯,安裝完成,你可以在控制面板的管理工具的服務(wù)中,看到你編寫的服務(wù)。
C#Windows服務(wù)程序開發(fā)7.
安裝好了之后在系統(tǒng)服務(wù)列表中可以管理服務(wù),這時要注意將服務(wù)的屬性窗口----登陸----“允許于桌面交互”勾選!這樣才能在啟動了你要的目標(biāo)程序后不單單存留于進(jìn)程。在桌面上也看得到。
C#Windows服務(wù)程序開發(fā)8.
關(guān)于卸載服務(wù),目前有兩個概念:一是禁用而已;一是完全刪除服務(wù)。 前者可以通過服務(wù)管理窗口直接完成。后者則需要進(jìn)入注冊表
“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服務(wù)名稱的文件夾,整個刪掉,重新啟動電腦后,服務(wù)消失。
C#Windows服務(wù)程序開發(fā)9.
擴(kuò)展思考:經(jīng)過修改代碼,還可以實現(xiàn):啟動目標(biāo)程序之前,檢測進(jìn)程中是否存在目標(biāo)程序,存在則不再次啟動。
C#Windows服務(wù)程序開發(fā)的實例的基本內(nèi)容就向你,希望對你學(xué)習(xí)和理解C#Windows服務(wù)程序開發(fā)有所幫助。
【編輯推薦】