.Net Windows服务无法访问文件

时间:2010-03-05 02:14:34

标签: .net windows web-services

我有VB.net Windows服务,其中一个函数是我使用的XML文件,它位于应用程序的同一目录中。

当我在服务启动时安装服务时,它找不到xml文件。如何在Web服务中包含XML文件?

如果我将文件复制到与exe和app.config文件相同的文件夹中,它仍然无法找到它。

3 个答案:

答案 0 :(得分:2)

与任何其他类型的应用程序一样,Windows服务通过路径定位文件。如果路径不是绝对路径,则当前目录路径是文件查找的一部分。

您应该确保知道当前目录是什么。显示System.Environment.CurrentDirectory并查看值是什么。

答案 1 :(得分:0)

试试这个:

using System.IO;
using System.Reflection;
.
.
.
string path =  Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); 
string fileName = Path.Join(path, "my_xml_file.xml");

然后尝试打开fileName。

能找到吗?

答案 2 :(得分:0)

使用Windows服务,它们是通过SvcHost.exe应用程序启动的,因此您的Windows服务基于该应用程序的上下文。尝试以这种方式建立路径:

private string GetPath()
{
    Assembly asm = Assembly.GetAssembly(typeof(MyClass));
    return asm.Location;
}

这应该为您提供服务EXE文件的完整路径,您可以从该文件中提取目录,然后将XML文件名合并到该文件中。

相关问题