Getting full path for Windows Service

C#.NetWindows Services

C# Problem Overview


How can I find out the folder where the windows service .exe file is installed dynamically?

Path.GetFullPath(relativePath);

returns a path based on C:\WINDOWS\system32 directory.

However, the XmlDocument.Load(string filename) method appears to be working against relative path inside the directory where the service .exe file is installed to.

C# Solutions


Solution 1 - C#

Try

System.Reflection.Assembly.GetEntryAssembly().Location

Solution 2 - C#

Try this:

AppDomain.CurrentDomain.BaseDirectory

(Just like here: https://stackoverflow.com/questions/2833959/how-to-find-windows-service-exe-path)

Solution 3 - C#

Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)

Solution 4 - C#

This works for our windows service:

//CommandLine without the first and last two characters
//Path.GetDirectory seems to have some difficulties with these (special chars maybe?)
string cmdLine = Environment.CommandLine.Remove(Environment.CommandLine.Length - 2, 2).Remove(0, 1);
string workDir = Path.GetDirectoryName(cmdLine);  

This should give you the absolute path of the executable.

Solution 5 - C#

Another version of the above:

string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;

Solution 6 - C#

Environment.CurrentDirectory returns current directory where program is running. In case of windows service, returns %WINDIR%/system32 path that is where executable will run rather than where executable deployed.

Solution 7 - C#

This should give you the path that the executable resides in:

Environment.CurrentDirectory;

If not, you could try:

Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName

A more hacky, but functional way:

Path.GetFullPath("a").TrimEnd('a')

:)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamuel KimView Question on Stackoverflow
Solution 1 - C#Greg DeanView Answer on Stackoverflow
Solution 2 - C#Curtis YallopView Answer on Stackoverflow
Solution 3 - C#allwarrView Answer on Stackoverflow
Solution 4 - C#lowgliderView Answer on Stackoverflow
Solution 5 - C#Chris SView Answer on Stackoverflow
Solution 6 - C#AmzathView Answer on Stackoverflow
Solution 7 - C#TheSoftwareJediView Answer on Stackoverflow