MJR
MJR

Reputation: 169

Where do I put supplemental files in a Windows Service?

Ok, here's the situation. I have written a Windows service. Testing it as a "console" app has shown promising results.

Unfortunately, I can't figure out where to put a file. I have some JSON data that is critical to the application. It's in a file. I'd rather not go into too much detail on that, but just know it has to be in a file,and it's critical. It's not a config file, but it is definitely needed.

Anyway, I've added the file to my windows service project. The problem is, I can't quite figure out the right code and settings to use to put the file in the right place when the service gets installed.

This is only the second Windows service I have ever written, and the first one (years ago) didn't require supplemental files.

I wrote the service in Visual Studio 2015, on Windows 7. I will be testing it on my local machine here at the office, but it will eventually go on a production machine.

Help, please? Any ideas as to where I should put the file and how I should reference it in code?

I saw a site that said I should use the following:

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

But that didn't seem to help when I did this:

filePath = Environment.CurrentDirectory + "\\myfile.ext"

File paths have never really been a strong suit of mine in these instances.

Any help here is greatly appreciated.

Upvotes: 0

Views: 481

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36318

I haven't tested this, but I see no reason why it wouldn't work:

internal string FilePath = 
    System.IO.Path.Combine(
      System.AppDomain.CurrentDomain.BaseDi‌​rectory, 
      Settings.Default.JsonFile);

Upvotes: 4

MJR
MJR

Reputation: 169

Ok, it looks like I got this figured out. I did the following:

  1. In my actual "Service" project, I added the file I needed.
  2. In the "program" of the service, I did the following:

    System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

    ServiceBase[] ServicesToRun;

    ServicesToRun = new ServiceBase[] { new MyService() };

    ServiceBase.Run(ServicesToRun);

And within the class that monitors everything, I have the following:

internal string FilePath = Directory.GetCurrentDirectory() + "\\" + Settings.Default.JsonFile;

Then there were a few other tweaks that I made that aren't relevant to this topic, but the above seemed to do the trick.

Upvotes: 0

Related Questions