C#Windows服務(wù)程序開(kāi)發(fā)實(shí)例介紹
C#Windows服務(wù)程序開(kāi)發(fā)實(shí)例程序的目的和用途:
很多開(kāi)機(jī)啟動(dòng)程序僅僅加在啟動(dòng)項(xiàng)里面,只有登陸后才真正啟動(dòng)。windows服務(wù)在開(kāi)機(jī)未進(jìn)行用戶登錄前就啟動(dòng)了。正是利用這一點(diǎn),解決一些服務(wù)器自動(dòng)重啟后特定軟件也自動(dòng)啟動(dòng)的問(wèn)題。
C#Windows服務(wù)程序開(kāi)發(fā)1.
新建一個(gè)服務(wù)項(xiàng)目 visual C#----windows----windows服務(wù);
C#Windows服務(wù)程序開(kāi)發(fā)2.
添加一個(gè)dataset(.xsd),用于存儲(chǔ)啟動(dòng)目標(biāo)的路徑,日志路徑等。
在dataset可視化編輯中,添加一個(gè)datatable,包含兩列 StartAppPath 和 LogFilePath。分別用于存儲(chǔ)目標(biāo)的路徑、日志路徑。
我認(rèn)為利用dataset.xsd存儲(chǔ)配置參數(shù)的優(yōu)勢(shì)在于可以忽略xml解析的具體過(guò)程直接使用xml文件。
在dataset中 提供了ReadXml方法用于讀取xml文件并將其轉(zhuǎn)換成內(nèi)存中的一張datatable表,數(shù)據(jù)很容易取出來(lái)!同樣,WriteXml方法用于存儲(chǔ)為xml格式的文件,也僅僅需要一句話而已。
C#Windows服務(wù)程序開(kāi)發(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)用程序的主入口點(diǎn)。
- /// ﹤/summary﹥
- static void Main()
- {
- ServiceBase[] ServicesToRun;
- // 同一進(jìn)程中可以運(yùn)行多個(gè)用戶服務(wù)。若要將
- // 另一個(gè)服務(wù)添加到此進(jìn)程中,請(qǐng)更改下行以
- // 創(chuàng)建另一個(gè)服務(wù)對(duì)象。例如,
- //
- // 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)用程序的主入口點(diǎn)。
- /// ﹤/summary﹥
- static void Main()
- {
- ServiceBase[] ServicesToRun;
- // 同一進(jìn)程中可以運(yùn)行多個(gè)用戶服務(wù)。若要將
- // 另一個(gè)服務(wù)添加到此進(jìn)程中,請(qǐng)更改下行以
- // 創(chuàng)建另一個(gè)服務(wù)對(duì)象。例如,
- //
- // ServicesToRun = new ServiceBase[] {
- new Service1(), new MySecondUserService()};
- //
- ServicesToRun = new ServiceBase[] {
- new WindowsServices_AutoStart() };
- ServiceBase.Run(ServicesToRun);
- }
- }
- }
C#Windows服務(wù)程序開(kāi)發(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, "找不到幫助文件路徑。
- 文件是否被改動(dòng)或刪除?\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, "
- 找不到幫助文件路徑。文件是否被改動(dòng)或刪除?\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ù)程序開(kāi)發(fā)5.
啟動(dòng)調(diào)試,成功時(shí)也會(huì)彈出一個(gè)對(duì)話框大致意思是提示服務(wù)需要安裝。
C#Windows服務(wù)程序開(kāi)發(fā)6.
把Debug文件夾下面的.exe執(zhí)行程序,安裝為windows系統(tǒng)服務(wù),安裝方法網(wǎng)上很多介紹。我說(shuō)一種常用的:
C#Windows服務(wù)程序開(kāi)發(fā)之安裝服務(wù)
訪問(wèn)項(xiàng)目中的已編譯可執(zhí)行文件所在的目錄。
用項(xiàng)目的輸出作為參數(shù),從命令行運(yùn)行 InstallUtil.exe。在命令行中輸入下列代碼:
installutil yourproject.exe
C#Windows服務(wù)程序開(kāi)發(fā)之卸載服務(wù)
用項(xiàng)目的輸出作為參數(shù),從命令行運(yùn)行 InstallUtil.exe。
installutil /u yourproject.exe
至此,整個(gè)服務(wù)已經(jīng)編寫,編譯,安裝完成,你可以在控制面板的管理工具的服務(wù)中,看到你編寫的服務(wù)。
C#Windows服務(wù)程序開(kāi)發(fā)7.
安裝好了之后在系統(tǒng)服務(wù)列表中可以管理服務(wù),這時(shí)要注意將服務(wù)的屬性窗口----登陸----“允許于桌面交互”勾選!這樣才能在啟動(dòng)了你要的目標(biāo)程序后不單單存留于進(jìn)程。在桌面上也看得到。
C#Windows服務(wù)程序開(kāi)發(fā)8.
關(guān)于卸載服務(wù),目前有兩個(gè)概念:一是禁用而已;一是完全刪除服務(wù)。 前者可以通過(guò)服務(wù)管理窗口直接完成。后者則需要進(jìn)入注冊(cè)表
“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服務(wù)名稱的文件夾,整個(gè)刪掉,重新啟動(dòng)電腦后,服務(wù)消失。
C#Windows服務(wù)程序開(kāi)發(fā)9.
擴(kuò)展思考:經(jīng)過(guò)修改代碼,還可以實(shí)現(xiàn):?jiǎn)?dòng)目標(biāo)程序之前,檢測(cè)進(jìn)程中是否存在目標(biāo)程序,存在則不再次啟動(dòng)。
C#Windows服務(wù)程序開(kāi)發(fā)的實(shí)例的基本內(nèi)容就向你,希望對(duì)你學(xué)習(xí)和理解C#Windows服務(wù)程序開(kāi)發(fā)有所幫助。
【編輯推薦】