.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、添加安装程序,如下图:

    4

5、设置相关属性,如下图:

     图1

     5

 

     图2

      6

6、安装服务(生产之前必须编译),打开“Visual Studio 命令提示”,定位到项目.exe文件目录,执行命令为:

     installutil srvWatchCoomputer.exe

     8

7、到此服务安装ok了

 

8、卸载服务命令为:

定位到项目.exe文件目录,执行命令为:

     installutil srvWatchCoomputer.exe /u

    9

 

 

备注:在操作过程中如果serviceProcessInstaller1中的属性Account值不是LocalService,在启动服务时为推出如下错误

    10

    查看系统日志保错信息如下:

无法启动服务。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了。

转载于:https://www.cnblogs.com/rockhe/archive/2011/10/15/2213764.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值