在哪里存储可以 运行 作为控制台应用程序或作为服务的应用程序的配置文件

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

目前,我的应用程序是一个 C# 控制台应用程序,但我现在收到请求使其能够 运行 作为 windows 服务器上的一项服务。

我已经根据这个例子编辑了我的代码:.NET console application as Windows service但是我正在努力处理我的配置和日志文件。

目前,我在 Environment.SpecialFolder.ApplicationData + @"\MyApplication\" 下将我的应用程序所需的 3 个文件存储到 运行,但我想如果我想 运行 它作为服务或作为同一台机器上的控制台应用程序(一次一个或另一个)并访问相同的配置文件。

我应该在哪里存储这些文件?

附加信息:将执行 CLI 的用户具有管理员权限。

我们在 windows 服务中使用 app.config 文件。

如果您的配置变量只是键值对,您可以使用 app.config 并使用

访问它
var yourParameterConfigValue = ConfigurationManager.AppSettings["parameterName"]

或者只创建一个 configuration.json 文件和适当的 c# class,使用

反序列化内容
//read configuration.json
var yourConfigObject = JsonConvert.DeserializeObject<MyConfig>(yourConfigString);

Environment.SpecialFolder.ApplicationData 将在应用程序 运行ning 的路径中包含用户名。

控制台应用程序将 运行 作为管理员(或其他),服务将 运行 作为 SYSTEM 用户。所以,路径会有所不同。

更好的选择是应用程序路径。您可以获取适用于控制台和服务的应用程序路径如下:

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