Reputation: 3626
I have a project in Visual Studio that generates an executable. I've created a Windows Service from that executable. Whenever I run it, it fails with the following error:
Error 1053: The service did not respond to the start or control request in a timely fashion.
After looking at Windows Event Viewer, I've found out that I'm getting a FileNotFoundException which is located at the working directory of the project. This is the portion that opens the file:
using (StreamReader file = File.OpenText("configSet.json"))
{
JsonSerializer serializer = new JsonSerializer();
configSet = (ConfigSet)serializer.Deserialize(file, typeof(ConfigSet));
}
This works perfectly fine whenever I run the service in Visual Studio or from the command prompt. For some reason this doesn't work when I try to start it as a Windows Service.
I've also found out that hard-coding the path to the file works fine when starting it up as a Windows Service.
I would like to avoid this and use the relative path if possible (so I don't have to perform a code check to determine if I'm running the service from Visual Studio, a command prompt, or as a Windows Service).
Upvotes: 1
Views: 1842
Reputation: 7696
You can get the path of the executable by using reflection and set current directory to it. Here is example how to do it:
String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
path = System.IO.Path.GetDirectoryName(path);
Directory.SetCurrentDirectory(path);
Upvotes: 3