相对路径的问题与.net Windows服务..? [英] Relative Path issue with .Net Windows Service..?

查看:142
本文介绍了相对路径的问题与.net Windows服务..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗口服务,试图从应用程序目录访问XML文件。

I have a windows service which is trying to access an xml file from the Application directory.

Windows服务安装目录:C:\ SERVICES \为MyService \ MyService.exe
xml文件的路径:C:\ SERVICES \为MyService \ MyService.xml

Windows Service Installed directory : C:\Services\MyService\MyService.exe
Path of the xml file : C:\Services\MyService\MyService.xml

我想用下面的code访问该文件。

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.

找不到文件:C:\ WINDOWS \ SYSTEM32 \ MyService.xml

"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.

推荐答案

有这个优雅的解决方案,从以下链接。

There is an elegant solution for this from the following link.

<一个href="http://haacked.com/archive/2004/06/29/current-directory-for-windows-service-is-not-what-you-expect.aspx/" rel="nofollow">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

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory) 

在运行它的服务例如。

static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                RunAsService();
            }
            else
            {
                RunAsConsole();
            }
        }

这篇关于相对路径的问题与.net Windows服务..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆