[c#] Windows service on Local Computer started and then stopped error

Usually, I get this error: (The "service name" service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other service or programs) when there's something wrong with my code, like non-existing drive paths, etc. The windows service will not start.

I have a windows service that backs up folder/files, to a location if it reached the size limit. Details are all provide by an XML Configuration that the windows service reads on start. I have a separate windows forms that has a button that does exactly what my windows service's onstart is doing. I use my windows forms for debugging the code before I put it in my windows service.

When I start my windows forms. It does what it suppose to do. When I put my code in the windows service OnStart() method the error showed up.

Here's my code:

protected override void OnStart(string[] args)
{

    private static string backupConfig = @"D:\LogBackupConfig\backupconfig.xml";
    private static string serviceStat = @"D:\LogBackupConfig\Status.txt";
    private static string fileFolderStat = @"D:\LogBackupConfig\FileFolderStat.txt";

    protected override void OnStart(string[] args)
    {
        if (File.Exists(backupConfig))
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            XmlTextReader reader = new XmlTextReader(backupConfig);

            XmlNodeType type;
            List<string> listFile = new List<string>();
            string fileWatch = "";

            //this loop is for reading XML elements and assigning to variables
            while (reader.Read())
            {
                type = reader.NodeType;
                if (type == XmlNodeType.Element)
                {
                    if (reader.Name == "File")
                    {
                        reader.Read();
                        fileWatch = reader.Value;
                    }
                    else if (reader.Name == "Folder")
                    {
                        reader.Read();
                        fileWatch = reader.Value;
                    }
                }
            }
            reader.Close();

            watcher.Path = fileWatch;
            watcher.Filter = "*.*";

            //this loop reads whether the service will watch a file/folder
            XmlTextReader reader1 = new XmlTextReader(backupConfig);
            while (reader1.Read())
            {
                type = reader1.NodeType;
                if (type == XmlNodeType.Element)
                {
                    if (reader1.Name == "File")
                    {
                        watcher.IncludeSubdirectories = false;
                        watcher.Changed += new FileSystemEventHandler(OnChangedFile);
                    }
                    else if (reader1.Name == "Folder")
                    {
                        watcher.IncludeSubdirectories = true;
                        watcher.Changed += new FileSystemEventHandler(OnChangedFolder);
                    }
                }
            }
            reader1.Close();

            watcher.EnableRaisingEvents = true;

        }
        else
        {
            StreamWriter sw = new StreamWriter(serviceStat, true);
            sw.WriteLine("File not found. Please start the Log Backup UI first.");
            sw.Close();
        }
    }

I don't know what keeps the windows service not starting, the windows form simulator worked fine. What seems to be the problem?

UPDATE: After many trials I've noticed that using only a folder directory (w/out file), the windows service doesn't work. When I replaced the fileWatch variable with a specific file (including its directory), the windows service started. When I changed it back to a folder location, it didn't work. What I think is that folder locations doesn't work in a filewatcher.

When I tried creating a new windows service that watches a folder location, it worked.. However, when I tried the same location in my original windows service, it didn't work! I was mindf$#*ed! It seems that I have to create a new windows service and build the installer everytime I place a new code/function.. This way I can keep track where I get an error.

This question is related to c# windows-services

The answer is


Please check that you have registered all HTTP endpoints in the local mahcine's Access Control List (ACL)

http://just2thepoint.blogspot.fr/2013/10/windows-service-on-local-computer.html


In our case, nothing was added in the Windows Event Logs except logs that the problematic service has been started and then stopped.

It turns out that the service's CONFIG file was invalid. Correcting the invalid CONFIG file fixed the issue.


I have found it very handy to convert your existing windows service to a console by simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it

program.cs

class Program
{
    static void Main()
    {
        var program = new YOUR_PROGRAM();
        if (Environment.UserInteractive)
        {
            program.Start();
        }
        else
        {
            ServiceBase.Run(new ServiceBase[]
            {
                program
            });
        }
    }
}

YOUR_PROGRAM.cs

[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
    public YOUR_PROGRAM()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Start();
    }

    protected override void OnStop()
    {
        //Stop Logic Here
    }

    public void Start()
    {
        //Start Logic here
    }
}

Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:

protected override void OnStart(string[] args)
{
     System.Diagnostics.Debugger.Launch();
     ...
}

than you could attach your visual studio to the process and have better debug abilities.

hope this was helpful, good luck


I came across the same issue. My service is uploading/receiving XMLS and write the errors to the Event Log.

When I went to the Event Log, I tried to filter it. It prompt me that the Event Log was corrupted.

I cleared the Event Log and all OK.


EventLog.Log should be set as "Application"


The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig.

Your watcher of type FileSystemWatcher is a local variable, and is out of scope when the OnStart method is done. You probably need it as an instance or class variable.


You may want to unit test the initialization - but because it's in the OnStart method this is near to impossible. I would suggest moving the initialization code out into a separate class so that it can be tested or at least re-used in a form tester.

Secondly to add some logging (using Log4Net or similar) and add some verbose logging so that you can see details about runtime errors. Examples of runtime errors would be AccessViolation etc. especially if your service is running without enough privileges to access the config files.


Use Timer and tick event to copy your files.

On start the service, start the time and specify the interval in the time.

So the service is keep running and copy the files ontick.

Hope it help.


Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:

"Service on local computer started and then stopped. some services stop automatically..."