2012-04-29 70 views
37

我有一个Windows服务应该在当前目录中查找配置文件。Windows服务 - 获取当前目录

于是我就用directory.getcurrentdirectiry()但不是服务目录,我回去

c:\windows\system32 

任何想法,为什么我应该怎么弄的服务目录?

回答

6

不要使用Directory.GetCurrentDirectory()。我与C:\ Windows \ System32被返回的问题具有相同的确切问题。使用这个来代替:

Path.GetDirectoryName(Application.ExecutablePath);

+0

显然你需要添加System.Windows.Forms.dll为了这个工作。 –

+0

我得到“名称应用程序在当前上下文中不存在” – red888

26

试试这个:

System.Reflection.Assembly.GetEntryAssembly().Location 
+0

此行给我,serviec运行的目录,而且大会本身... sonthig像 - C:\ serviceDir \ APP.EXE我想只有目录 – MoShe

+0

@摩西 - 这是完整的道路。 – coder

+2

Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()。Location) – VhsPiceros

88

您可以将当前目录设置为您服务是由包括该行代码运行的目录:

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

这样做的重要组成部分,是:

System.AppDomain.CurrentDomain.BaseDirectory 

返回到您的服务运行目录的路径。从完整路径

+4

'System.AppDomain.CurrentDomain.BaseDirectory'为我工作,它给出了目录。 'System.Reflection.Assembly.GetEntryAssembly()。Location'返回目录加可执行文件的名称 – j00hi

+0

@ j00hi是的,谢谢澄清:D – Jed

+1

这个答案对不同的场景更好。我使用NCrunch,并且接受的答案对此没有帮助。 – reydelleon

15

获取目录:

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

相当比较编写一个窗口服务,当一个愚蠢的问题:)

+0

它可以帮助我。谢谢 – phanvugiap

2

string applicationDir = AppDomain.CurrentDomain.BaseDirectory;