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

C#Windows服务启动后没有响应,c#,windows-services,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 Syst

我想在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;
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统诊断;
使用System.Linq;
使用System.ServiceProcess;
使用系统文本;
使用System.IO;
使用System.Threading.Tasks;
//使用系统线程;
名称空间转换服务
{
公共部分类WindowsService:ServiceBase
{
公共服务
{
初始化组件();
this.ServiceName=“TOUTransference”;
this.EventLog.Log=“应用程序”;
//这些标志设置是否处理该特定事件
//事件类型。如果需要,请将其设置为true,否则设置为false。
this.CanHandlePowerEvent=true;
this.CanHandleSessionChangeEvent=true;
this.CanPauseAndContinue=true;
this.CanShutdown=true;
this.CanStop=true;
}
System.Threading.Timer TimerItem;
/// 
///OnStart():将启动代码放在此处
///-启动线程、获取初始数据等。
/// 
/// 
启动时受保护的覆盖无效(字符串[]args)
{
尝试
{
ServiceController服务=新的ServiceController(“ToTransference”、“);
if(service.Status==ServiceControllerStatus.Running)
WriteLog(“流程已启动”);
base.OnStart(args);
}
捕获(异常错误)
{
犯错误;
}
}
/// 
///OnStop():在此处输入停止代码
///-停止线程,设置最终数据等。
/// 
受保护的覆盖void OnStop()
{
尝试
{
ServiceController服务=新的ServiceController(“ToTransference”、“);
if(service.Status==ServiceControllerStatus.Stopped)
写日志(“进程已停止”);
base.OnStop();
}
捕获(异常错误)
{
犯错误;
}
}
私有void WriteLog(字符串文本)
{
尝试
{
StreamWriter sw=新的StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+@“\test.txt”,true);
sw.WriteLine(DateTime.Now.ToString()+“:“+text+”\n”);
sw.Close();
}
捕获(异常错误)
{
犯错误;
}
}
}
}
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()
        {

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Configuration.Install;
使用System.ServiceProcess;
使用系统组件模型;
名称空间转换服务
{
[运行安装程序(true)]
公共类WindowsServiceInstaller:安装程序
{
/// 
///WindowsServiceInstaller的公共构造函数。
///-将所有初始化代码放在此处。
/// 
公共WindowsServiceInstaller()
{
ServiceProcessInstaller ServiceProcessInstaller=
新的ServiceProcessInstaller();
ServiceInstaller=新的ServiceInstaller();
//#服务帐户信息
serviceProcessInstaller.Account=ServiceAccount.LocalSystem;
serviceProcessInstaller.Username=null;
serviceProcessInstaller.Password=null;
//#服务信息
serviceInstaller.DisplayName=“TOU传输”;
serviceInstaller.StartType=ServiceStartMode.Automatic;
//#这必须与WindowsService.ServiceBase名称相同
//#在WindowsService.cs的构造函数中设置
serviceInstaller.ServiceName=“TOUTransference”;
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
私有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);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.ServiceProcess;
使用系统文本;
使用System.Threading.Tasks;
名称空间转换服务
{
静态类程序
{
/// 
///应用程序的主要入口点。
/// 
静态void Main()
{
ServiceBase[]ServicesToRun;
ServicesToRun=新的ServiceBase[]
{ 
新WindowsService()
};
ServiceBase.Run(ServicesToRun);
}
}
}

首先,您正在检查
if(service.Status==ServiceControllerStatus.Running)
而您真正应该检查
if(service.Status==ServiceControllerStatus.startpend)
,因为您尚未完成启动


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

它是文本文件的位置

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

您可以:

  • 将文件放在独立于执行用户的位置(如C:\…),或硬编码用户桌面文件夹的物理路径(C:\users\[yourname]\desktop\…)。硬编码是一个坏习惯