簡體   English   中英

C#Windows服務啟動后沒有響應

[英]C# Windows service not respond after started

我希望在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);
        }
    }
}

首先,您正在檢查if (service.Status == ServiceControllerStatus.Running)何時應該檢查if (service.Status == ServiceControllerStatus.StartPending)因為您還沒有完成Start。

其次,確保您正在運行服務的用戶(無論是本地系統還是特定用戶)都有權編輯您嘗試將文件寫入的文件夾。

它是您的文本文件的位置

如果服務作為LocalSystem運行,則“Environment.SpecialFolder.Desktop”文件夾與桌面文件夾不同。

你可以:

  • 將文件放在獨立於執行用戶的位置(如C:\\ ..),或將物理路徑硬編碼到用戶的桌面文件夾(C:\\ users \\ [yourname] \\ Desktop \\ ...)。 但硬編碼是一種不好的做法。
  • 修改服務,使其作為您自己的用戶運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM