开发者

.Net Windows Service not able to access a file

开发者 https://www.devze.com 2022-12-21 20:14 出处:网络
I have VB.net windows service and in one of the 开发者_运维知识库functions I am using a XML file which is in the same directory of the application.

I have VB.net windows service and in one of the 开发者_运维知识库functions I am using a XML file which is in the same directory of the application.

When I install the service though the service starts it is not finding the xml file. How do I include the XML file in the web service?

If I copy the file to the same folder as the exe and app.config files, it is still not able to find it.


Like any other kind of application, a Windows Service locates files through a path. If the path is not absolute, then the current directory path is part of the file lookup.

You should make sure you know what your current directory is. Display System.Environment.CurrentDirectory and see what the value is.


Try this:

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

And then try and open the fileName.

Can it find this?


With Windows services, they are launched through the SvcHost.exe application, so your windows service is based on the context of that application. Try basing the path this way instead:

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

That should get you the full path to the service EXE file, from which you can extract the directory and then combine the XML file name to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号