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

时间:2014-09-25 13:27:46

标签: c# windows-services

我想在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()
        {

        }
    }
}

Program.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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

首先,您正在检查if (service.Status == ServiceControllerStatus.Running)何时应该检查if (service.Status == ServiceControllerStatus.StartPending),因为您尚未完成“开始”。

其次,确保您正在运行服务的用户(无论是本地系统还是特定用户)都有权编辑您尝试将文件写入的文件夹。

答案 1 :(得分:1)

这是您的文本文件的位置

如果服务以LocalSystem运行,则“Environment.SpecialFolder.Desktop”文件夹与桌面文件夹不同。

你可以:

  • 将文件放在独立于执行用户的位置(如C:\ ..),或者将物理路径硬编码到用户的桌面文件夹(C:\ users \ [yourname] \ Desktop \ ... )。硬编码虽然不好。
  • 修改服务,使其以自己的用户身份运行