What Is the Equivalent of Application. Executablepath in Windows Service
In a Windows Forms Application, I Use Application. Executable Path to Get to the App. Config. , I Need to Get to App. Config in Windows Service. . What Would...
In a windows forms application, I use Application.Executable path to get to the App.config.,
I need to get to app.config in Windows Service.. What would that be ?
4 Answers
A couple of options:
System.Reflection.Assembly.GetExecutingAssembly().Location
For the current assembly. or, you can derive it from a type:
System.Reflection.Assembly.GetAssembly(typeof(MyAssemblyType)).Location
Then (on either) you can use Path.GetDirectoryName to get the folder it's originating from (assuming your app.config is within that same directory).
Have a look at AppDomain.BaseDirectory Property
Gets the base directory that the assembly resolver uses to probe for assemblies.
The most common usage would be similar to
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
Possible options are:
AppDomain.CurrentDomain.BaseDirectory
OR
Assembly.Location
OR
Assembly.GetExecutingAssembly().CodeBase
Personally, I used the last one.
You can use ConfigurationManager to read App.config :
Add a reference to
System.Configurationto your project.Use
ConfigurationManagerlike this to read App.config :ConfigurationManager.AppSettings["KeySample"]In the config file you can add your keys like this :
<configuration> <appSettings> <add key="KeySample" value="SampleValue"/> </appSettings> </configuration>So you don't have to get the path.