Windows service - get current directory

自古美人都是妖i 提交于 2019-12-03 06:28:16

问题


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?


回答1:


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

Path.GetDirectoryName(Application.ExecutablePath);




回答2:


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.




回答3:


Try this:

System.Reflection.Assembly.GetEntryAssembly().Location



回答4:


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



来源:https://stackoverflow.com/questions/10376253/windows-service-get-current-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!