Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run an EXE program from a Windows Service using C#?

How can I run an EXE program from a Windows Service using C#?

This is my code:

System.Diagnostics.Process.Start(@"E:\PROJECT XL\INI SQLLOADER\ConsoleApplication2\ConsoleApplication2\ConsoleApplication2\bin\Debug\ConsoleApplication2.exe"); 

When I run this service, the application is not starting.
What's wrong with my code?

like image 407
xoops Avatar asked Mar 15 '11 05:03

xoops


People also ask

Can a Windows service run an EXE?

Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.

How do you call a Windows service method in C#?

Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name the project "TestWindowsService" as shown in the following screenshot. After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen.


1 Answers

This will never work, at least not under Windows Vista or later. The key problem is that you're trying to execute this from within a Windows Service, rather than a standard Windows application. The code you've shown will work perfectly in a Windows Forms, WPF, or Console application, but it won't work at all in a Windows Service.

Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.

More information is available in the answers to these related questions:

  • How can a Windows Service start a process when a Timer event is raised?
  • which process in windows is user specific?
  • windows service (allow service to interact with desktop)

The best solution to your problem, as you've probably figured out by now, is to create a standard Windows application instead of a service. These are designed to be run by a particular user and are associated with that user's desktop. This way, you can run additional applications whenever you want, using the code that you've already shown.

Another possible solution, assuming that your Console application does not require an interface or output of any sort, is to instruct the process not to create a window. This will prevent Windows from blocking the creation of your process, because it will no longer request that a Console window be created. You can find the relevant code in this answer to a related question.

like image 124
Cody Gray Avatar answered Sep 20 '22 03:09

Cody Gray