How to Run Console Application from Windows Service

How to run console application from Windows Service?

Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.

On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.

If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.

ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;

Process process = Process.Start(info);

See if this does the trick.

First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).

Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput and process.StandardOutput.

.NET console application as Windows service

I usually use the following techinque to run the same app as a console application or as a service:

using System.ServiceProcess

public static class Program
{
#region Nested classes to support running as service
public const string ServiceName = "MyService";

public class Service : ServiceBase
{
public Service()
{
ServiceName = Program.ServiceName;
}

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

protected override void OnStop()
{
Program.Stop();
}
}
#endregion

static void Main(string[] args)
{
if (!Environment.UserInteractive)
// running as service
using (var service = new Service())
ServiceBase.Run(service);
else
{
// running as console app
Start(args);

Console.WriteLine("Press any key to stop...");
Console.ReadKey(true);

Stop();
}
}

private static void Start(string[] args)
{
// onstart code here
}

private static void Stop()
{
// onstop code here
}
}

Environment.UserInteractive is normally true for console app and false for a service. Techically, it is possible to run a service in user-interactive mode, so you could check a command-line switch instead.

Run a Windows Service as a console app

Before a Windows Service can run, it has to be "installed" first using installutil. EG:

C:\installutil -i c:\path\to\project\debug\service.exe

Then you can open up the list of Services to start it. EG:

  1. Right click 'My Computer'
  2. Click on 'Manage'
  3. Open up 'Services and Applications'
  4. Click on 'Services'
  5. Find your service in the list and right-click on it
  6. Click on 'Start'

Once it has started, you can go into Visual Studio, click on 'Debug', then click on 'Attach to Process'.

Another technique is to add this line to your OnStart() method in the service:

System.Diagnostics.Debugger.Launch();

When you do that, it'll prompt you to pick an instance of Visual Studio to debug the service in.

How to Run a windows service as console application on client machine

Use the Debug.WriteLine in your code and view all these Strings using the DbgView and this will not need the Console to be open.

Simple as

System.Diagnostics.Debug.WriteLine("Your Debug String Here");

Invoke console app from windows service

There is probably some permissions issue there (PdfReportGeneration.exe inaccessible under service account or maybe something that it uses...)
I would advise to capture Process Monitor log to see where exactly it fails.

Run the Console Application as service

Use File->New Project->Visual C#->Windows->Windows Service,

And Add your main code to OnStart(), and OnStop() event handlers, then install it as a service:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace MyWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

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

protected override void OnStop()
{
}
}
}

.NET Core 3.1 Console App as a Windows Service

I forgot about answering this question as I solved it a few hours later after I asked it, but you can just add ".UseWindowsService()" to the Host.CreateDefaultBuilder(args) line.
eg:

 public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() //<==== THIS LINE
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();

Running a C# console application as a Windows service

You cannot just take any console application and run as Windows service. First you need to implement your service class that would inherit from ServiceBase, then in entry point (Main) you need to run the service with ServiceBase.Run(new YourService()). In your service class you need to define what happens when service starts and ends.

Ideally you should add ServiceInstaller to your assembly too. This way you will be able to preset your service properties, and use installutil.exe to install the service.

C# Running console application as windows service - The service didn't respond error

I tried your exact steps and it worked for me. I will highlight a few key points that I came across

  1. OnStart should definitely return in a timely fashion. i.e. the work should happen in a separate process/thread. I used your code for thread and it worked fine for me.
  2. Make sure the executable is on a local drive which can be accessed from your "Local System" account without any permission issues.
  3. Make sure when you create the service, you provide the absolute path and not relative path.
  4. Make sure the sc create ... command responds back with [SC] CreateService SUCCESS
  5. Check the service was created in the service control panel
  6. Make sure you can start it from the service control panel before attempting it from command line
  7. Also, open task manager or process explorer to make sure the service executable is running or not (irrespective of what status is returned by service control panel or scm start)
  8. For debugging, I logged the information into a local temp file - again watch out for permissions issues with Local System account.
  9. If for whatever reasons you have to delete the service, make sure that it indeed disappeared from the service control panel


Related Topics



Leave a reply



Submit