74

I have a Windows service that should look for a configuration file in its current directory.

So I use directory.getcurrentdirectiry() but instead of the service directory I get back

c:\windows\system32

Any idea why and how should I get the service directory?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MoShe
  • 6,197
  • 17
  • 51
  • 77

5 Answers5

173

You can set the current directory to the directory that your service is running from by including this line in your code:

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

The important part of this is:

System.AppDomain.CurrentDomain.BaseDirectory

That returns the path to the directory your service is running from.

Jed
  • 8,022
  • 3
  • 19
  • 19
  • 11
    `System.AppDomain.CurrentDomain.BaseDirectory` worked for me, it gives the directory. `System.Reflection.Assembly.GetEntryAssembly().Location` returns the directory plus the name of the executable – j00hi Jun 03 '14 at 18:00
  • 1
    This answer works better for different scenarios. I use NCrunch, and the accepted answer wouldn't help there. – Reydel Leon Aug 04 '16 at 19:11
  • 1
    This also works in a broader set of environments (asp.net, winform, and windows services) as compared to other solutions like Assembly.Location and etc. – Brian Gideon Sep 20 '16 at 15:48
  • 2
    System.AppDomain.CurrentDomain.BaseDirectory worked for me. Also I made a test using it both as Windows Service and Console Application (inside Linux Container) and works fine in both scenarios! Thanks! :D – gatsby Dec 11 '18 at 12:10
33

Try this:

System.Reflection.Assembly.GetEntryAssembly().Location
coder
  • 13,002
  • 31
  • 112
  • 214
  • This line give me the directory that the serviec is running BUT also the Assembly itself... sonthig like - c:\serviceDir\app.exe I would like only the directory – MoShe Apr 30 '12 at 22:08
  • 7
    Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) – VhsPiceros Dec 30 '15 at 20:19
20

Getting directory from full path:

var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directoryPath = Path.GetDirectoryName(location);

Quite a silly problem when comparing to writing a Windows service :)

Pang
  • 9,564
  • 146
  • 81
  • 122
Michael Brennt
  • 731
  • 9
  • 20
15

Don't use Directory.GetCurrentDirectory(). I had the same exact problem with C:\Windows\System32 being returned. Use this instead:

Path.GetDirectoryName(Application.ExecutablePath);

puffgroovy
  • 240
  • 2
  • 5
2

In case you're targeting .NET Core or .NET Standard you could use AppContext.BaseDirectory as well.

See https://learn.microsoft.com/en-us/dotnet/api/system.appcontext.basedirectory

Kai Thoma
  • 512
  • 4
  • 14