1

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).

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
Roka545
  • 3,404
  • 20
  • 62
  • 106
  • Where is your json file? – Samvel Petrosov May 11 '17 at 17:25
  • 1
    @S.Petrosov In the root folder of my generated project folder. Basically, I have a project in Visual Studio. I published it to my Desktop which results in a folder with required dlls, folders, etc. This folder includes the executable that I create the service out of. It also contains the json file. I take this entire folder and move it to Program Files. After that I create the service via: sc.exe create MY.SERVICE binpath= "C:\Program Files\myService\myService.exe – Roka545 May 11 '17 at 17:28
  • 1
    File is most likely not in the correct path. A service runs from a different directory than where the executable is located. http://stackoverflow.com/questions/884963/what-directory-does-a-windows-service-run-in – bgura May 11 '17 at 17:32

1 Answers1

3

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);
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46