.Net Windows服务(一):VS快速创建一个简单Windows服务
在项目中经常会遇见一些电脑开机就需要运行服务去处理事情这样的需求,那么这里简单记录一下创建一个服务的简单流程(服务任务:记录开机时间与开机登录用户到指定文件中)
1、创建Windows项目srvWatchComputer,并把Service1.cs改成WatchComputer
2、在WatchComputer的设计视图中拖入控件EventLog,用于记录日志(此处可以添加自己需要的控件)
3、打开WatchComputer代码视图,在OnStart中实现业务逻辑如下
protected override void OnStart(string[] args)
{
StreamWriter swr;
string path = "c:\\watchComputer.txt";
try
{
if (!File.Exists(path))
{
File.Create(path,0, FileOptions.Asynchronous);
}
}
catch (Exception)
{
eventLog1.WriteEntry("文件没有找到~~");
}
swr = File.AppendText(path);
swr.WriteLine("本地系统启动时间-->" + DateTime.Now.ToString());
swr.WriteLine("本次系统登录用户-->" + Environment.GetEnvironmentVariable("UserName"));
swr.Close();
}
4、添加安装程序,如下图:
5、设置相关属性,如下图:
图1
图2
6、安装服务(生产之前必须编译),打开“Visual Studio 命令提示”,定位到项目.exe文件目录,执行命令为:
installutil srvWatchCoomputer.exe
7、到此服务安装ok了
8、卸载服务命令为:
定位到项目.exe文件目录,执行命令为:
installutil srvWatchCoomputer.exe /u
备注:在操作过程中如果serviceProcessInstaller1中的属性Account值不是LocalService,在启动服务时为推出如下错误
查看系统日志保错信息如下:
无法启动服务。System.Security.SecurityException: 未找到源,不过,未能搜索部分或所有事件日志。若要创建源,您需要用于读取所有事件日志的权限以确保新的源名称是唯一的。不可访问的日志: Security。
在 System.Diagnostics.EventLogInternal.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
在 System.Diagnostics.EventLogInternal.SourceExists(String source, String machineName, Boolean wantToCreate)
在 System.Diagnostics.EventLogInternal.VerifyAndCreateSource(String sourceName, String currentMachineName)
在 System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
在 System.Diagnostics.EventLog.WriteEntry(String message)
在 srvWatchComputer.WatchComputer.OnStart(String[] args) 位置 E:\C#\Code\Demo\WindowsSevers\WindowsServerDemo\srvWatchComputer\WatchComputer.cs:行号 33
在 System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
失败的程序集的区域是:
MyComputer
那么把这个Accout属性值设置成LocalSystem,重新编译与部署服务就ok了。