0

I am reading a file that is located in the same directory as my executable using a StreamReader with the following method:

StreamReader reader=new StreamReader(".\\file.txt"); //NOTE: 2nd backslash is escape character in C#

When I do this in the debug environment, it reads the file fine, but when I install the service it tries to read the file in C:\Windows\System32\ as if the working directory is set to that path, but in the services properties there is no working directory option. I'm guessing it's using the working dir of sc.exe.

Is there a way I can get it to resolve to the location of the current executable using relative file paths? Because the service might be placed in different locations based on deployments.

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
Stuyvenstein
  • 2,340
  • 1
  • 27
  • 33

1 Answers1

0

Yes, working directory of a service is %WinDir%\System32.Also GetModuleFileName() will return incorrect result because your service is hosted by another executable (by chance placed in that directory too).

You have to find executing assembly and its location, longer to describe than to do:

string assemblyPath = Assembly.GetExecutingAssembly().Location;

Now just extract directory name and combine with file you want:

string path = Path.Combine(Path.GetDirectoryName(assemblyPath), "file.txt");
Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208