Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of the Development example of C # Windows Service Program

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "C # Windows service program development case analysis". In daily operation, I believe that many people have doubts about C # Windows service program development case analysis. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "C # Windows service program development case analysis". Next, please follow the editor to study!

The purpose and purpose of C#Windows service program development example program:

Many boot programs are only added to the startup items and only start after logging in. The windows service starts before the user logs in. It is to take advantage of this point to solve the problem that specific software also starts automatically after some servers are automatically restarted.

C#Windows service program development 1.

Create a new service project visual C#----windows----windows service

C#Windows service program development 2.

Add a dataset (.xsd) to store the path of the startup target, log path, and so on.

In dataset visual editing, add a datatable with two columns StartAppPath and LogFilePath. The path and log path used to store the target respectively.

I think the advantage of using dataset.xsd to store configuration parameters is that you can ignore the specific process of xml parsing and use the xml file directly.

The ReadXml method is provided in dataset to read the xml file and convert it into a datatable table in memory, and the data is easy to fetch! Similarly, the WriteXml method can be used to store files in xml format with only one sentence.

C#Windows service program development 3.

The program.cs file serves as the program entry, and the code is as follows:

View plaincopy to clipboardprint? Using System.Collections.Generic; using System.ServiceProcess; using System.Text; namespace WindowsServices_AutoStart {static class Program {/ / < summary > / / the main entry point of the application. / / < / summary > static void Main () {ServiceBase [] ServicesToRun; / / multiple user services can be run in the same process. To add / / another service to this process, change the following line to / / create another service object. For example, / 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 > / / the main entry point of the application. / / < / summary > static void Main () {ServiceBase [] ServicesToRun; / / multiple user services can be run in the same process. To add / / another service to this process, change the following line to / / create another service object. For example, / ServicesToRun = new ServiceBase [] {new Service1 (), new MySecondUserService ()}; / / ServicesToRun = new ServiceBase [] {new WindowsServices_AutoStart ()}; ServiceBase.Run (ServicesToRun);}

C#Windows service program development 4.

Service.cs master file, the code is as follows:

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; / / notice path / / proc.StartInfo.Arguments = "; proc.Start ();} catch (System.Exception ex) {/ / MessageBox.Show (this," help file path not found. Has the file been altered or deleted? \ n "+ ex.Message," prompt, 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: add code here to perform the shutdown required to stop the service. 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 / / notice the path / / proc.StartInfo.Arguments = ""; proc.Start ();} catch (System.Exception ex) {/ / MessageBox.Show (this, "the help file path cannot be found. Has the file been altered or deleted? \ n "+ ex.Message," prompt, 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: add code here to perform the shutdown required to stop the service. 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 service program development 5.

Start debugging, and when successful, a dialog box will pop up, roughly indicating that the service needs to be installed.

C#Windows service program development 6.

The .exe execution program under the Debug folder is installed as a windows system service, and the installation method is introduced on the Internet. I'm talking about a common one:

Installation services for C#Windows service program development

Access the directory where the compiled executable is located in the project.

Run InstallUtil.exe from the command line with the output of the project as an argument. Enter the following code on the command line:

Installutil yourproject.exe

Uninstall service for C#Windows service program development

Run InstallUtil.exe from the command line with the output of the project as an argument.

Installutil / u yourproject.exe

At this point, the entire service has been written, compiled, and installed, and you can see the service you wrote in the services of the management tools in the control panel.

C#Windows service program development 7.

After installation, you can manage the service in the list of system services. At this time, you should pay attention to check the properties window of the service-login-"allow desktop interaction"! In this way, you can not only save in the process after starting the target program you want. It can also be seen on the table.

C#Windows service program development 8.

There are currently two concepts about uninstalling the service: one is to disable it, and the other is to delete the service completely. The former can be done directly through the service management window. The latter needs to enter the registry.

"HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Services" finds the folder of the service name, deletes the whole folder, and the service disappears after restarting the computer.

C#Windows service program development 9.

Extended thinking: after modifying the code, it can also be achieved: before starting the target program, detect whether there is a target program in the process, and do not start again if it exists.

At this point, the study on the "C # Windows service program development example analysis" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report