Santosh
Santosh

Reputation: 124

Getting Error on start method of windows service

I have created a windows service by using (Visual Studio 8) and installed it by using installutil.exe tool, however I am not getting proper result from it as I did the following code on service start method.

protected override void OnStart(string[] args)
{
    FileStream fs = new FileStream(@"e:\mcWindowsService.txt",
        FileMode.OpenOrCreate, FileAccess.Write);
    StreamWriter m_streamWriter = new StreamWriter(fs);
    m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    m_streamWriter.WriteLine("m ready buddy");
    m_streamWriter.Flush();
    m_streamWriter.Close();
}

Instead of creating file in E Drive it is showing Following Error when I am staring it !

The Test Service Installer service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or program.

Upvotes: 0

Views: 579

Answers (3)

Mircea Ion
Mircea Ion

Reputation: 698

I'm almost positive your code crashes. The try-catch suggestion above is the best so far so you can see what blows up.

Further: Try to not execute stuff that takes a long time in the OnStart - only light initialization stuff. There's a timeout and if you go past that treshold Windows will complain that it cannot start it - it will remain in Starting state which is annoying. In OnStart start just a timer and execute your heavy stuff in the handler of the expiration event of that timer's interval timer_Elapsed. Before you execute your stuff pause the timer and start it back after the operation ended.

Upvotes: 0

Toan Nguyen
Toan Nguyen

Reputation: 11591

If you run the service from the a console, then make sure that your account has permissions on the E driver.

If you have installed your service, and realized that it threw the exception, then set the account type for the service installer like

var serviceInstaller = new ServiceProcessInstaller();
            serviceInstaller.Account = ServiceAccount.LocalSystem;

Upvotes: 0

Cinchoo
Cinchoo

Reputation: 6322

Put the above code in Try-Catch block, write it to event log for any exceptions and investigate it. Also would be good to put them in separate thread to avoid any block.

Upvotes: 2

Related Questions