|
新建项目,选windows服务 如图
起名WriteLogs,将Service1.cs改名为WriteLogs.cs,编辑该文件 ,先建三个字段。
- private Task t;
- private CancellationTokenSource cts;
- private string logs = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs.txt");
复制代码 建一个方法InitializeTask ,初始化任务。
- private void InitializeTask()
- {
- cts = new CancellationTokenSource();
- cts.Token.Register(() =>
- {
- if(File.Exists(logs))
- {
- using (StreamWriter sw = new StreamWriter(logs, true))
- {
- sw.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss 运行结束"));
- }
- }
- }
- );
-
- t = new Task(DoWriteLogs, logs);
- }
复制代码 再建一个任务调用的方法,在方法中随便做点什么。
- private void DoWriteLogs(object o)
- {
- string logs = o as string;
- CancellationToken token = cts.Token;
- while (true)
- {
- if (token.IsCancellationRequested)
- {
- token.ThrowIfCancellationRequested();
- break;
- }
- if (File.Exists(logs))
- {
- using (StreamWriter sw = new StreamWriter(logs, true))
- {
- sw.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss 运行中..."));
- }
- }
- else
- {
- using (StreamWriter sw = File.CreateText(logs))
- {
- sw.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss 运行中..."));
- }
- }
- Task.Delay(3000).Wait();
- }
- }
复制代码 把初始化的方法放入构造函数中
- public WriteLogs()
- {
- InitializeComponent();
- InitializeTask();
- }
复制代码 开始任务
- protected override void OnStart(string[] args)
- {
- if (t.Status != TaskStatus.Running)
- t.Start();
- }
复制代码 停止任务
- protected override void OnStop()
- {
- cts.Cancel();
- }
复制代码
服务的主体就写好了,在WriteLogs的设计界面,右击添加安装程序,在ProjectInstaller.cs设计界面可以看到添加了二个文件,一个是serviceinstaller1,一个是serviceProcessInstaller1,选中serviceinstaller1,在属性界面,将ServiceName属性改为我们自己的服务名:WriteLogs,将StartType属性改为Automatic。选中ServiceProcessInstaller1,在属性界面将Account改为LocalSystem。至此,服务完成了,可以生成该服务。
第二段,右击解决方案,添加《新建项目》,选wpf应用,起名为LogsManager,将界面设计成下图
引用System.ServiceProcess;System.Configuration.Install 见下图
注意using名称空间,先设计二个字段
- private string _servicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WriteLogs.exe");
- private string _serviceName = "WriteLogs";
复制代码 然后编写判断服务是否存在的方法
- private bool IsServiceExist(string serviceName)
- {
- bool isExist = false;
- foreach(var service in ServiceController.GetServices())
- {
- if (service.ServiceName == serviceName)
- isExist = true;
- else isExist = false;
- }
- return isExist;
- }
复制代码 安装服务方法
- private void InstallService(string servicePath)
- {
- using (AssemblyInstaller installer = new AssemblyInstaller())
- {
- installer.UseNewContext = true;
- installer.Path = servicePath;
- using (TransactedInstaller transactedInstaller = new TransactedInstaller())
- {
- transactedInstaller.Installers.Add(installer);
- transactedInstaller.Install(new System.Collections.Hashtable());
- }
- }
- }
复制代码 卸载服务的方法
- private void UninstallService(string servicePath)
- {
- using (AssemblyInstaller installer = new AssemblyInstaller())
- {
- installer.UseNewContext = true;
- installer.Path = servicePath;
- using (TransactedInstaller transactedInstaller = new TransactedInstaller())
- {
- transactedInstaller.Installers.Add(installer);
- transactedInstaller.Uninstall(null);
- }
- }
- }
复制代码 启动服务的方法
- private void StartService(string serviceName)
- {
- using (ServiceController sc = new ServiceController(serviceName))
- {
- if (sc.Status == ServiceControllerStatus.Stopped)
- sc.Start();
- }
- }
复制代码 停止服务的方法
- private void StopService(string serviceName)
- {
- using (ServiceController sc = new ServiceController(serviceName))
- {
- if (sc.Status == ServiceControllerStatus.Running)
- sc.Stop();
- }
- }
复制代码 然后编写各个按钮的click事件
- private void Exit_Click(object sender, RoutedEventArgs e)
- {
- Application.Current.Shutdown();
- }
- private void Uninstall_Click(object sender, RoutedEventArgs e)
- {
- if(IsServiceExist(_serviceName))
- {
- StopService(_serviceName);
- UninstallService(_servicePath);
- if(!IsServiceExist(_serviceName))
- {
- txtInfo.Text = "信息:服务已经卸载";
- }
- }
- }
- private void Stop_Click(object sender, RoutedEventArgs e)
- {
- if(IsServiceExist(_serviceName))
- {
- StopService(_serviceName);
- txtInfo.Text = "信息:服务停止";
- }
- }
- private void Start_Click(object sender, RoutedEventArgs e)
- {
- if(IsServiceExist(_serviceName))
- {
- StopService(_serviceName);
- StartService(_serviceName);
- txtInfo.Text = "信息:服务启动";
- }
- }
- private void Install_Click(object sender, RoutedEventArgs e)
- {
- if(!IsServiceExist(_serviceName))
- {
- InstallService(_servicePath);
- txtInfo.Text = "信息:服务已安装";
- }
- }
复制代码 右击LogsManager,添加应用程序清单文件,这是很重要的一步,决定了服务能否成功安装。
立刻弹出这个界面
<requestedExecutionLevel level="asInvoker" uiAccess="false" /> 改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 至此才算大功造成,运行这个wpf项目,会弹出这个界面
点击使用其他凭据重新启动,visual studio 2017重新启动后,再运行程序,把先前的服务文件WriteLogs.exe 复制到wpf当前目录下,可以试试,安装服务,启动服务看看,一切OK。
WriteLogs.rar
(79.23 KB, 下载次数: 5)
|
-
|