C#Windows服务启动后没有响应

本文关键字:响应 服务 启动 C#Windows | 更新日期: 2023-09-27 18:24:32

我想在Windows服务启动后将一些字符串写入文本文件,但启动后没有任何响应。我的代码出了什么问题?

WindowsService.cs

    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;
    using System.Threading.Tasks;
    //using System.Threading;
    namespace TOU_Transference_Service
    {
        public partial class WindowsService : ServiceBase
        {
            public WindowsService()
            {
                InitializeComponent();
                this.ServiceName = "TOUTransference";
                this.EventLog.Log = "Application";
                // These Flags set whether or not to handle that specific
                //  type of event. Set to true if you need it, false otherwise.
                this.CanHandlePowerEvent = true;
                this.CanHandleSessionChangeEvent = true;
                this.CanPauseAndContinue = true;
                this.CanShutdown = true;
                this.CanStop = true;
            }
            System.Threading.Timer TimerItem;

            /// <summary>
            /// OnStart(): Put startup code here
            ///  - Start threads, get inital data, etc.
            /// </summary>
            /// <param name="args"></param>
            protected override void OnStart(string[] args)
            {
                try
                {
                    ServiceController service = new ServiceController("TOUTransference", ".");
                    if (service.Status == ServiceControllerStatus.Running)
                        WriteLog("Process Started");
                    base.OnStart(args);
                }
                catch (Exception err)
                {
                    throw err;
                }
            }
            /// <summary>
            /// OnStop(): Put your stop code here
            /// - Stop threads, set final data, etc.
            /// </summary>
            protected override void OnStop()
            {
                try
                {
                    ServiceController service = new ServiceController("TOUTransference", ".");
                    if (service.Status == ServiceControllerStatus.Stopped)
                        WriteLog("Process Stopped");
                    base.OnStop();
                }
                catch (Exception err)
                {
                    throw err;
                }
            }
        private void WriteLog(string text)
        {
            try
            {
                StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"'test.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + " : " + text + "'n");
                sw.Close();
            }
            catch (Exception err)
            {
                throw err;
            }
        }
    }
}

WindowsServiceInstaller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
namespace TOU_Transference_Service
{
    [RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {
        /// <summary>
        /// Public Constructor for WindowsServiceInstaller.
        /// - Put all of your Initialization code here.
        /// </summary>
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller =
                               new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();
            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;
            //# Service Information
            serviceInstaller.DisplayName = "TOU Transference";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "TOUTransference";
            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
        private void InitializeComponent()
        {
        }
    }
}

程序.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace TOU_Transference_Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new WindowsService() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

C#Windows服务启动后没有响应

首先,您在检查if (service.Status == ServiceControllerStatus.Running),而实际上您应该检查if (service.Status == ServiceControllerStatus.StartPending),因为您还没有完成Start。

第二,确保您运行服务的用户(无论是本地系统还是特定用户)有权编辑您试图将文件写入的文件夹。

它是文本文件的位置

如果服务以LocalSystem运行,则文件夹"Environment.SpecialFolder.DDesktop"与您的桌面文件夹不同。

您可以:

  • 将文件放在独立于执行用户的位置(如C:''..),或对用户桌面文件夹的物理路径进行硬编码(C:''users''[yourname]''desktop''…)。不过,硬编码是一种糟糕的做法
  • 修改服务,使其以您自己的用户身份运行