C # implement a Windows Service for starting other programs

Source: Internet
Author: User
Today, I decided to write a blog. I don't want to do anything else. I just want to accumulate my own resources. It would be better if I could not mislead others or even give some inspiration to my friends at the same time!

ProgramPurpose and purpose:

Many boot programs are only added to the boot items and can only be started after login. Windows Services are started before user logon. This solves the problem of Automatic startup of specific software after the server is automatically restarted.

1. Create a service project Visual C # ---- windows ---- Windows service;

2. Add a dataset (. XSD) to store the startup target path and Log Path.

In dataset visual editing, add a able that contains two columns: startapppath and logfilepath. Used to store the target path and Log Path 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 directly use XML files.

The readxml method is provided in dataset to read XML files and convert them into a able table in memory. The data can be easily retrieved! Similarly, the writexml method is used to store files in XML format, and only one sentence is required.

3. Use the program. CS file as the program portal,CodeAs follows:

View plaincopy to clipboardprint?
Using system. Collections. Generic;
Using system. serviceprocess;
Using system. text;

Namespace windowsservices_autostart
{
Static class Program
{
/// <Summary>
/// 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. Please change the downstream
// 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
{< br> static class Program
{< br> ///


// main entry point of the application.
//
static void main ()
{< br> servicebase [] servicestorun;

// Multiple user services can be run in the same process. To
// Add another service to this process. Please change the downstream
// Create another service object. For example,
//
// Servicestorun = new servicebase [] {New service1 (), new myseconduserservice ()};
//
Servicestorun = new servicebase [] {New windowsservices_autostart ()};

Servicebase. Run (servicestorun );
}
}
}

4. Main file of service. CS, 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; // note the path
// Proc. startinfo. Arguments = "";
Proc. Start ();
}
Catch (system. Exception ex)
{
// MessageBox. Show (this, "the path to the Help file cannot be found. Is the file modified 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 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; // note the path
// Proc. startinfo. Arguments = "";
Proc. Start ();
}
Catch (system. Exception ex)
{
// MessageBox. Show (this, "the path to the Help file cannot be found. Is the file modified 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 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
{

}
}
}
}

5. When debugging is started, a dialog box is displayed, indicating that the service needs to be installed.

6.install the. exe program under the debug folder as a Windows system service. There are many installation methods on the Internet. I am talking about a common method:

Install services
Access the directory of compiled executable files in the project.
Use the project output as a parameter to run installutil.exe from the command line. Enter the following code in the command line:
Installutil yourproject.exe
Uninstall Service
Use the project output as a parameter to run installutil.exe from the command line.
Installutil/u yourproject.exe

Now, the entire service has been compiled, compiled, and installed. You can see the service you have compiled in the service of the management tool on the control panel.

7. After the installation is complete, you can manage the service in the System Service list. In this case, check the service attribute window-login-"allow desktop interaction! In this way, the target program you want will not survive the process alone. You can also see it on the desktop.

8. There are two concepts about detaching a service: first, disabling the service and deleting the service completely. The former can be directly completed through the Service Management window. The latter needs to go to the Registry "HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services" and find the folder of the service name. The entire folder is deleted. After the computer is restarted, the Service disappears.

9. Extended thinking: After modifying the code, you can also: Before starting the target program, check whether the target program exists in the process. If yes, do not start it again.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.