59

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.

Samuel Kim
  • 3,723
  • 2
  • 22
  • 18

7 Answers7

84

Try

System.Reflection.Assembly.GetEntryAssembly().Location
Greg Dean
  • 28,129
  • 14
  • 64
  • 76
70

Try this:

AppDomain.CurrentDomain.BaseDirectory

(Just like here: How to find windows service exe path)

Community
  • 1
  • 1
Curtis Yallop
  • 5,990
  • 3
  • 42
  • 29
  • 2
    Thanks for this. I had an NServiceBus service, and since it gets wrapped up in NServiceBus.Host.exe, the `GetEntryAssembly()` was null in my actual project. This one worked perfectly though. – Matt Feb 21 '14 at 15:37
39
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
5

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.

lowglider
  • 1,077
  • 2
  • 11
  • 21
5

Another version of the above:

string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;
Chris S
  • 63,624
  • 49
  • 218
  • 238
3

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.

Amzath
  • 3,039
  • 10
  • 30
  • 43
-4

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')

:)

TheSoftwareJedi
  • 33,542
  • 19
  • 105
  • 151
  • 5
    -1: Environment.CurrentDirectory and your hacky solution both return the current working directory, which from what the OP says is the system32 directory. – Joe Oct 14 '08 at 09:24