.Net Windows 服务的相对路径问题..?
我有一个 Windows 服务,它试图从应用程序目录访问 xml 文件。
Windows服务安装目录:C:\Services\MyService\MyService.exe
xml 文件的路径:C:\Services\MyService\MyService.xml
我尝试使用以下代码访问该文件。
using (FileStream stream = new FileStream("MyService.xml", FileMode.Open, FileAccess.Read))
{
//Read file
}
我收到以下错误。
“找不到文件:C:\WINDOWS\system32\MyService.xml”
我的服务正在使用本地系统帐户运行,我不想使用绝对路径。
I have a windows service which is trying to access an xml file from the Application directory.
Windows Service Installed directory : C:\Services\MyService\MyService.exe
Path of the xml file : C:\Services\MyService\MyService.xml
I am trying to access the file using the following code.
using (FileStream stream = new FileStream("MyService.xml", FileMode.Open, FileAccess.Read))
{
//Read file
}
I get the following error.
"Can not find file : C:\WINDOWS\system32\MyService.xml"
My service is running with local system account and I don't want to use absolute path.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下链接提供了一个优雅的解决方案。
http://haacked.com/archive/2004/06/29/current-directory-for-windows-service-is-not-what-you-expect.aspx/
因为我的服务都作为控制台运行/service 我刚刚
在将其作为服务运行之前调用,例如
There is an elegant solution for this from the following link.
http://haacked.com/archive/2004/06/29/current-directory-for-windows-service-is-not-what-you-expect.aspx/
As my service is running both as console/service I just called
before running it as Service E.g.
当 Windows 服务启动时,当前目录是系统目录,正如您所发现的那样。用于将相对路径解析为绝对路径的是当前目录,而不是您的应用程序(服务)目录。 (如果您想确认这一点,请检查
Environment.CurrentDirectory
变量。)以下辅助方法可能会在这里派上用场:
然后您可以将其用作:
然后路径将解析为
C: \Services\MyService\MyService.xml
,如您所愿。When a Windows Service is launched, the current directory is the system directory, as you indeed seem to be finding. It is the current directory that is used to resolve relative paths into absolute paths, not your application (service) directory. (Check the
Environment.CurrentDirectory
variable if you want to confirm this.)The following helper method may come in handy here:
Which you can then use as:
The path will then resolve to
C:\Services\MyService\MyService.xml
, as you want.您需要找到服务程序集的路径,如下所示:
You need to find the path to your service's assembly, like this: