reference :
http://msdn.microsoft.com/en-us/zt39148a.aspx
1.In a solution, right click the solution and choose "add new project" ; add a "Windows Service" as below, name it as "MyWinService"
2.The project looks like this:
3. F2 ,rename "Service1.cs" to "MyWinService.cs"
4.As shown in the above, on the left grey area, right click and select "Add Installer"
5.changed properties for the installer, remember to change the "account" value to "Local System", as shown in the following screen shot:
6.MyWindService.cs code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace MyWinService
{
publicpartialclassMyWinService : ServiceBase
{
public MyWinService()
{
InitializeComponent();
}
privatestring folderPath = @"D:\temp";
protectedoverridevoid OnStart(string[] args)
{
if (!System.IO.Directory.Exists(folderPath))
System.IO.Directory.CreateDirectory(folderPath);
FileStream fs = newFileStream(folderPath + "\\WindowsService.txt",
FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter m_streamWriter = newStreamWriter(fs);
m_streamWriter.BaseStream.Seek(0,SeekOrigin.End);
m_streamWriter.WriteLine(" WindowsService: Service Started at " +
DateTime.Now.ToShortDateString() + " " +
DateTime.Now.ToShortTimeString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protectedoverridevoid OnStop()
{
FileStream fs = newFileStream(folderPath +
"\\WindowsService.txt",
FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter m_streamWriter = newStreamWriter(fs);
m_streamWriter.BaseStream.Seek(0,SeekOrigin.End);
m_streamWriter.WriteLine(" WindowsService: Service Stopped at " +
DateTime.Now.ToShortDateString() + " " +
DateTime.Now.ToShortTimeString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
}
}
7.Ctrl+Shit+B to build the project , in my case, the bin folder : C:\Projects\VS_2010_Proj\ConsoleApplication1\MyWinService\bin\Debug, you will see the MyWinService.exe
8.Now, launch the Visual Studio Command Prompt (in Windowns 7 remember to run the command prompt as Administrator) (in theStart Menu -> Programs -> Microsoft Visual Studio -> Visual Studio Tools).
install :
C:\Projects\VS_2010_Proj\ConsoleApplication1\MyWinService\bin\Debug>installutil
MyWinService.exe
[uninstall
C:\Projects\VS_2010_Proj\ConsoleApplication1\MyWinService\bin\Debug>installutil
MyWinService.exe /u
]
Once installed, you should see something like this:
9.Start /stop the service to check the log.