Windows服务 - 获取当前目录

MoS*_*She 50 c# windows-services working-directory

我有一个Windows服务,应该在其当前目录中查找配置文件.

所以我使用directory.getcurrentdirectiry()但不是服务目录我回来了

c:\windows\system32
Run Code Online (Sandbox Code Playgroud)

知道为什么以及如何获得服务目录?

Jed*_*Jed 127

您可以通过在代码中包含以下行来将当前目录设置为运行服务的目录:

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
Run Code Online (Sandbox Code Playgroud)

其中重要的部分是:

System.AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)

这将返回运行服务的目录的路径.

  • `System.AppDomain.CurrentDomain.BaseDirectory`为我工作,它给出了目录.`System.Reflection.Assembly.GetEntryAssembly().Location`返回目录加上可执行文件的名称 (6认同)
  • System.AppDomain.CurrentDomain.BaseDirectory 为我工作。我还使用它作为 Windows 服务和控制台应用程序(在 Linux 容器内)进行了测试,并且在两种情况下都可以正常工作!谢谢!:D (2认同)

cod*_*der 30

试试这个:

System.Reflection.Assembly.GetEntryAssembly().Location
Run Code Online (Sandbox Code Playgroud)

  • Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()位置) (3认同)

Mic*_*nnt 16

从完整路径获取目录:

var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directoryPath = Path.GetDirectoryName(location);
Run Code Online (Sandbox Code Playgroud)

与编写Windows服务相比,这是一个非常愚蠢的问题:)


小智 12

不要用Directory.GetCurrentDirectory().我有与C:\ Windows\System32返回相同的问题.请改用:

Path.GetDirectoryName(Application.ExecutablePath);

  • 显然,您需要添加System.Windows.Forms.dll才能使其正常工作. (3认同)