C#实现一个用于开机启动其他程序的Windows服务
生活随笔
收集整理的這篇文章主要介紹了
C#实现一个用于开机启动其他程序的Windows服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天決定寫寫博客,不為別的,只當自己的積累,如果與此同時能不誤導他人甚至給了朋友們一些啟發,那真是更好了!
程序的目的和用途:
很多開機啟動程序僅僅加在啟動項里面,只有登陸后才真正啟動。windows服務在開機未進行用戶登錄前就啟動了。正是利用這一點,解決一些服務器自動重啟后特定軟件也自動啟動的問題。
1.新建一個服務項目 visual C#----windows----windows服務;
2.添加一個dataset(.xsd),用于存儲啟動目標的路徑,日志路徑等。
?? 在dataset可視化編輯中,添加一個datatable,包含兩列 StartAppPath 和 LogFilePath。分別用于存儲目標的路徑、日志路徑。
?? *我認為利用dataset.xsd存儲配置參數的優勢在于可以忽略xml解析的具體過程直接使用xml文件。
???? 在dataset中 提供了ReadXml方法用于讀取xml文件并將其轉換成內存中的一張datatable表,數據很容易取出來!同樣,WriteXml方法用于存儲為xml格式的文件,也僅僅需要一句話而已。
3. program.cs文件 作為程序入口,代碼如下:
view plaincopy to clipboardprint?
using System.Collections.Generic;??
using System.ServiceProcess;??
using System.Text;??
??
namespace WindowsServices_AutoStart??
{??
????static class Program??
????{??
????????/// <summary>??
????????/// 應用程序的主入口點。??
????????/// </summary>??
????????static void Main()??
????????{??
????????????ServiceBase[] ServicesToRun;??
??
????????????// 同一進程中可以運行多個用戶服務。若要將??
????????????// 另一個服務添加到此進程中,請更改下行以??
????????????// 創建另一個服務對象。例如,??
????????????//??
????????????//?? 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>
????????/// 應用程序的主入口點。
????????/// </summary>
????????static void Main()
????????{
????????????ServiceBase[] ServicesToRun;
????????????// 同一進程中可以運行多個用戶服務。若要將
????????????// 另一個服務添加到此進程中,請更改下行以
????????????// 創建另一個服務對象。例如,
????????????//
????????????//?? ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
????????????//
????????????ServicesToRun = new ServiceBase[] { new WindowsServices_AutoStart() };
????????????ServiceBase.Run(ServicesToRun);
????????}
????}
}
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: 在此處添加代碼以執行停止服務所需的關閉操作。??
????????????????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: 在此處添加代碼以執行停止服務所需的關閉操作。
????????????????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
????????????{
????????????}
????????}
????}
}
5.啟動調試,成功時也會彈出一個對話框大致意思是提示服務需要安裝。
6.把Debug文件夾下面的.exe執行程序,安裝為windows系統服務,安裝方法網上很多介紹。我說一種常用的:
安裝服務
訪問項目中的已編譯可執行文件所在的目錄。??
用項目的輸出作為參數,從命令行運行 InstallUtil.exe。在命令行中輸入下列代碼:??
installutil yourproject.exe
卸載服務??
用項目的輸出作為參數,從命令行運行 InstallUtil.exe。??
installutil /u yourproject.exe
至此,整個服務已經編寫,編譯,安裝完成,你可以在控制面板的管理工具的服務中,看到你編寫的服務。
7.安裝好了之后在系統服務列表中可以管理服務,這時要注意將服務的屬性窗口----登陸----“允許于桌面交互”勾選!這樣才能在啟動了你要的目標程序后不單單存留于進程。在桌面上也看得到。
8.關于卸載服務,目前有兩個概念:一是禁用而已;一是完全刪除服務。 前者可以通過服務管理窗口直接完成。后者則需要進入注冊表“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服務名稱的文件夾,整個刪掉,重新啟動電腦后,服務消失。
9.擴展思考:經過修改代碼,還可以實現:啟動目標程序之前,檢測進程中是否存在目標程序,存在則不再次啟動
程序的目的和用途:
很多開機啟動程序僅僅加在啟動項里面,只有登陸后才真正啟動。windows服務在開機未進行用戶登錄前就啟動了。正是利用這一點,解決一些服務器自動重啟后特定軟件也自動啟動的問題。
1.新建一個服務項目 visual C#----windows----windows服務;
2.添加一個dataset(.xsd),用于存儲啟動目標的路徑,日志路徑等。
?? 在dataset可視化編輯中,添加一個datatable,包含兩列 StartAppPath 和 LogFilePath。分別用于存儲目標的路徑、日志路徑。
?? *我認為利用dataset.xsd存儲配置參數的優勢在于可以忽略xml解析的具體過程直接使用xml文件。
???? 在dataset中 提供了ReadXml方法用于讀取xml文件并將其轉換成內存中的一張datatable表,數據很容易取出來!同樣,WriteXml方法用于存儲為xml格式的文件,也僅僅需要一句話而已。
3. program.cs文件 作為程序入口,代碼如下:
view plaincopy to clipboardprint?
using System.Collections.Generic;??
using System.ServiceProcess;??
using System.Text;??
??
namespace WindowsServices_AutoStart??
{??
????static class Program??
????{??
????????/// <summary>??
????????/// 應用程序的主入口點。??
????????/// </summary>??
????????static void Main()??
????????{??
????????????ServiceBase[] ServicesToRun;??
??
????????????// 同一進程中可以運行多個用戶服務。若要將??
????????????// 另一個服務添加到此進程中,請更改下行以??
????????????// 創建另一個服務對象。例如,??
????????????//??
????????????//?? 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>
????????/// 應用程序的主入口點。
????????/// </summary>
????????static void Main()
????????{
????????????ServiceBase[] ServicesToRun;
????????????// 同一進程中可以運行多個用戶服務。若要將
????????????// 另一個服務添加到此進程中,請更改下行以
????????????// 創建另一個服務對象。例如,
????????????//
????????????//?? ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
????????????//
????????????ServicesToRun = new ServiceBase[] { new WindowsServices_AutoStart() };
????????????ServiceBase.Run(ServicesToRun);
????????}
????}
}
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: 在此處添加代碼以執行停止服務所需的關閉操作。??
????????????????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: 在此處添加代碼以執行停止服務所需的關閉操作。
????????????????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
????????????{
????????????}
????????}
????}
}
5.啟動調試,成功時也會彈出一個對話框大致意思是提示服務需要安裝。
6.把Debug文件夾下面的.exe執行程序,安裝為windows系統服務,安裝方法網上很多介紹。我說一種常用的:
安裝服務
訪問項目中的已編譯可執行文件所在的目錄。??
用項目的輸出作為參數,從命令行運行 InstallUtil.exe。在命令行中輸入下列代碼:??
installutil yourproject.exe
卸載服務??
用項目的輸出作為參數,從命令行運行 InstallUtil.exe。??
installutil /u yourproject.exe
至此,整個服務已經編寫,編譯,安裝完成,你可以在控制面板的管理工具的服務中,看到你編寫的服務。
7.安裝好了之后在系統服務列表中可以管理服務,這時要注意將服務的屬性窗口----登陸----“允許于桌面交互”勾選!這樣才能在啟動了你要的目標程序后不單單存留于進程。在桌面上也看得到。
8.關于卸載服務,目前有兩個概念:一是禁用而已;一是完全刪除服務。 前者可以通過服務管理窗口直接完成。后者則需要進入注冊表“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服務名稱的文件夾,整個刪掉,重新啟動電腦后,服務消失。
9.擴展思考:經過修改代碼,還可以實現:啟動目標程序之前,檢測進程中是否存在目標程序,存在則不再次啟動
轉載于:https://www.cnblogs.com/freedom831215/archive/2009/10/03/1577669.html
總結
以上是生活随笔為你收集整理的C#实现一个用于开机启动其他程序的Windows服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神浮游干核怎么获得?
- 下一篇: Silverlight中文件的生成操作与