1. First create a Windows Service
2, after the creation of the switch to Code view, the code has the default OnStart and OnStop methods to perform service opening and service stop operation, the following code is explained in detail:
Using System;
Using System.IO;
usingsystem.serviceprocess;
Using System.Text;
Usingsystem.timers;
Namespacetestservice
{
public partial class Service1:servicebase
{
Public Service1 ()
{
InitializeComponent ();
}
protected override Voidonstart (string[] args)
{
Service Open Execution Code
Startdosomething ();
}
protected override void OnStop ()
{
Service End Execution Code
}
protected override void OnPause ()
{
Service paused execution Code
Base. OnPause ();
}
protected override void OnContinue ()
{
Service Recovery Execution Code
Base. OnContinue ();
}
protected override void OnShutdown ()
{
System is about to close execution code
Base. OnShutdown ();
}
private void Startdosomething ()
{
System.Timers.Timer Timer = NewSystem.Timers.Timer (10000); Interval 10 seconds
Timer. AutoReset = true;
Timer. Enabled = false; Execute once
Timer. Elapsed + = Newelapsedeventhandler (writesomething);
Timer. Start ();
}
private void Writesomething (Objectsource, System.Timers.ElapsedEventArgs e)
{
FileStream fs = null;
Try
{
FS = Newfilestream ("D:/1.txt", FileMode.OpenOrCreate);
String strText = @ "//instantiate a file stream---> associated with Write file
FileStream fs = Newfilestream (SF. FileName, FileMode.Create);
Instantiate a streamwriter--> associated with FS
StreamWriter SW = Newstreamwriter (FS);
Start writing
Sw. Write (This.textBox1.Text);
emptying buffers
Sw. Flush ();
Close the stream
Sw. Close ();
Fs. Close (); ";
Get byte array
byte[] data = newutf8encoding (). GetBytes (StrText);
Start writing
Fs. Write (data, 0, data. Length);
Empties the buffer, closes the stream
Fs. Flush ();
Fs. Close ();
Fs. Dispose ();
}
Catch
{
}
Finally
{
if (fs! = NULL)
{
Fs. Close ();
Fs. Dispose ();
}
}
}
}
}
3. Then switch to Design view, right-click on the "Add Installer" in circle
4. Select the first control, click F4, switch to the property view on the right, change the account property in the Properties view to LocalService (Local service)
5.
Select the second control above, click F4, and switch to the property view on the right. Change servicename for your own favorite service name, remember not to conflict with the system Oh ~, Pro! StartType default to Manual, you can change to automatic
(Automatic) or disabled (Disabled)
6. Compile the project, then win+r input cmd into the command window. To find InstallUtil.exe in the directory corresponding to the. NET version, my project uses. NET 2.0, so the path is C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
CMD command
InstallUtil Windowsservice_test.exe (installing Windows Services)
installutil/u windowsservice_test.exe (uninstall Windows service)
. Net Development Windows Service