How to read a text file from a windows service?

I made a windows service that installs into a directory c:\Program Files\My Service. Along with the executable, I have an XML file that is installed in the same directory. This XML file is used by the service to obtain user information.

In the service code, I read the file as if it were local to the executable. Example:

DataSet ds = new DataSet();
ds.ReadXml("Foo.xml");

However, when I start the service, the service throws an exception:

Could not find file 'C: \ Windows \ system32 \ Foo.xml'

Since the executable lives in c:\Program Files\My Service, I expected the Windows service to look for the XML file in c:\Program Files\My Service\Foo.xml. Obviously, this is not so.

How to make a service look for a (relatively) Foo.xml file in the same place where the service executable lives?

+5
3

:

System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Foo.xml");
+10

,

 DataSet ds = new DataSet();
 ds.ReadXml(System.IO.Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location,"Foo.xml");
0

The working directory for the Windows service is C: \ Windows \ System32.

To read your XML file, as expected, you should do this below

DataSet ds = new DataSet(); 
ds.ReadXml(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "Foo.xml")); 
0
source

All Articles