Search code examples
c#windowswindows-serviceswindows-server

Where to store the config files of an application that can be run as a console application or as a service


Currently, my application is a C# console application, but I now got the request to make it able to be run as a service on a windows server.

I already edited my code according to this example: .NET console application as Windows service but I am struggling with my config, and log files.

Currently, I stored 3 files which I require for my application to run under Environment.SpecialFolder.ApplicationData + @"\MyApplication\", but I suppose this won´t suit if I want to run it as a service OR as a console application on the same machine (either one or the other at a time) and access the same config files.

Where would I store those files?

Additional info: The user which would execute the CLI has Admin rights.


Solution

  • Environment.SpecialFolder.ApplicationData will include name of user in path with which the application is running.

    Console application will run as Administrator (or whatever) and services will run as SYSTEM user. So, the path will be different.

    Better alternative is application path. You can get the application path as follows which works for both Console and Service:

    private static string GetApplicationPath()
    {
        string assemblyPath = Assembly.GetEntryAssembly().CodeBase;
        assemblyPath = new Uri(assemblyPath).LocalPath;
        assemblyPath = Path.GetDirectoryName(assemblyPath);
        return assemblyPath;
    }