在 Windows 窗体应用程序中,我使用 Application.Executable 路径来访问 App.config。,
我需要在 Windows 服务中访问 app.config。那会是什么?
几个选项:
System.Reflection.Assembly.GetExecutingAssembly().Location
对于当前程序集。或者,您可以从类型派生它:
System.Reflection.Assembly.GetAssembly(typeof(MyAssemblyType)).Location
然后(在任何一个上)您都可以使用Path.GetDirectoryName
它来获取它源自的文件夹(假设您的 app.config 在同一目录中)。
获取程序集解析器用于探测程序集的基目录。
最常见的用法类似于
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
您可以使用 ConfigurationManager 来读取 App.config :
1) 将参考 System.Configuration 添加到您的项目中。
2)像这样使用 ConfigurationManager 来读取 App.config :
ConfigurationManager.AppSettings["KeySample"]
在配置文件中,您可以像这样添加密钥:
<configuration>
<appSettings>
<add key="KeySample" value="SampleValue"/>
</appSettings>
</configuration>
所以你不必得到路径。
可能的选项是
AppDomain.CurrentDomain.BaseDirectory
OR
Assembly.Location
OR
Assembly.GetExecutingAssembly().CodeBase
就个人而言,我使用了最后一个。