.Net Windows服务的相对路径问题..?

时间:2010-04-26 14:31:20

标签: .net file-io windows-services relative-path

我有一个Windows服务,它试图从Application目录访问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”

我的服务使用本地系统帐户运行,我不想使用绝对路径。

3 个答案:

答案 0 :(得分:27)

通过以下链接有一个优雅的解决方案。

http://haacked.com/archive/2004/06/29/current-directory-for-windows-service-is-not-what-you-expect.aspx/

由于我的服务作为控制台/服务运行,我刚刚调用

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory) 
在将其作为服务运行之前

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

答案 1 :(得分:4)

您需要找到服务程序集的路径,如下所示:

static readonly string assemblyPath = 
    Path.GetDirectoryName(typeof(MyClass).Assembly.Location);

using (FileStream stream = File.OpenRead(Path.Combine(assemblyPath, "MyService.xml"))

答案 2 :(得分:4)

启动Windows服务时,当前目录是系统目录,因为您确实正在查找。它是当前目录,用于将相对路径解析为绝对路径,而不是应用程序(服务)目录。 (如果要确认,请检查Environment.CurrentDirectory变量。)

以下辅助方法可能派上用场:

public static string GetAppRelativePath(string path)
{
    return Path.Combine(Path.GetDirectoryName(
        Assembly.GetEntryAssembly().Location), path);
}

然后您可以将其用作:

using (FileStream stream = new FileStream(Utilities.GetAppRelativePath(
    "MyService.xml"), FileMode.Open, FileAccess.Read))
{
    // Read file
}

然后,路径将根据需要解析为C:\Services\MyService\MyService.xml

相关问题