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

3
  • Where is your json file? May 11, 2017 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, 2017 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. stackoverflow.com/questions/884963/…
    – bgura
    May 11, 2017 at 17:32

1 Answer 1

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);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.