C # Windows Service - Run .exe from App.config

I am using the below code to execute an .exe file from a windows service.

System.Diagnostics.Process.Start(path);

      

Right now I have hardcoded the path as @ 'C: \ Program Files \ Server \ Test.exe' It works fine.

Now I want to avoid hardcoding. When I just use Test.exe it goes to C: \ Windows \ System32.

How can I dynamically set the set path from a Windows service? Or how can I read the path from the App.config file?

+3


source to share


3 answers


Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)



+5


source


If you are .net all the way down (i.e. your windows service is a .net application) you can use Assembly.GetEntryAssembly

(from the System.Reflection namespace):

var entryAssembly = Assembly.GetEntryAssembly();
var launchLocation = entryAssembly.Location;

      

Alternatively, you can check AppDomain

which one you are working in (assuming you are not doing anything smart with multiple of them!)

var appDomain = AppDomain.CurrentDomain;
var launchLocation = appDomain.BaseDirectory;

      

Simple console application:



static void Main(string[] args)
{
    var entryAssembly = Assembly.GetEntryAssembly();
    var launchLocationFromAssembly = entryAssembly.Location;


    var appDomain = AppDomain.CurrentDomain;
    var launchLocationFromAppDomain = appDomain.BaseDirectory;

    Console.WriteLine(launchLocationFromAssembly);
    Console.WriteLine(launchLocationFromAppDomain);
}

      

Gives the following output:

c: \ users \ robertwray \ documents \ visual studio 2015 \ Projects \ ConsoleApplication4 \ ConsoleApplication4 \ bin \ Debug \ ConsoleApplication4.exe

c: \ users \ robertwray \ documents \ visual studio 2015 \ Projects \ ConsoleApplication4 \ ConsoleApplication4 \ bin \ Debug \

This means that if you used Assembly

to extract the path, you will need to remove the name of the executable with the following:

var launchPathFromAssembly = Path.GetDirectoryName(launchLocationFromAssembly);

      

+1


source


you can use

AppDomain.CurrentDomain.BaseDirectory

      

+1


source







All Articles