Peter
Peter

Reputation: 13

C# Windows service not respond after started

I would like to write some string into text file after Windows service started, but it is not respond anything after started. What's wrong in my code?

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

Upvotes: 1

Views: 166

Answers (2)

Beemen
Beemen

Reputation: 108

It is the location of your text file

The folder "Environment.SpecialFolder.Desktop" is not the same as your desktop folder if the service runs as LocalSystem.

You can either:

  • Put the file in a place that is independent of the executing user (like C:\..), or hard coding the physical path to user's desktop folder (C:\users\[yourname]\Desktop\...). Hard coding is a bad practice though.
  • Modify the service so that it runs as your own user

Upvotes: 1

Adam Gritt
Adam Gritt

Reputation: 2674

First, you are checking if (service.Status == ServiceControllerStatus.Running) when you should really be checking if (service.Status == ServiceControllerStatus.StartPending) as you haven't completed the Start yet.

Second, make sure that the user you are running the service as (be it Local System, or a specific user) has permissions to edit the folder you are trying to write the file to.

Upvotes: 2

Related Questions