c# Windows服务是不是(可能)使用app.config

Posted

技术标签:

【中文标题】c# Windows服务是不是(可能)使用app.config【英文标题】:c# Windows service is it (possible) to use the app.configc# Windows服务是否(可能)使用app.config 【发布时间】:2014-12-18 08:28:56 【问题描述】:

我正在开发一个windows服务,我快完成了,

我正在使用 Visual Studio 2012 进行此操作。

我连接到App.config 文件是为了读取连接字符串,因为 Windows 服务处理安装在数据库中的数据。

我可以在我的机器上安装这个 Windows 服务,但是我想问这个服务在安装后是否仍然可以从App.config 读取?还是我必须硬编码连接字符串?

我希望我能够解释我的问题。但是,如果您不理解我,请告诉我更多信息。

最好的尊重,

【问题讨论】:

相关:***.com/questions/14074563/… 【参考方案1】:

是的,您将能够。编译服务时,您需要部署整个 /bin 目录。它将包含服务依赖项和实际代码。

编译后,App.config 文件将重命名为:Service.exe.config。内容将是App.config 的副本。这是服务将使用的文件。 Service.exe 是您的可执行文件的名称。所以如果你的可执行文件是AwesomeService.exe,那么配置文件就是AwesomeService.exe.config

【讨论】:

我以前使用installutil myservice.exe注册windows服务,请问如何注册整个bin文件夹? 我一般用sc create***.com/questions/3663331/…我把bin文件夹的内容复制到我想部署到的服务器上(不自动化的时候),里面包含你服务的.exe以及您的服务所依赖的.dll,只要.config 文件。【参考方案2】:

更简单的方法是根据特定路径读取特定的配置文件!这是一个工作示例:

System.Configuration.Configuration conf = System.Configuration.ConfigurationManager.OpenExeConfiguration("<full path including component name.exe (and not including the '.config' part");
string PropValue = conf.AppSettings.Settings["PropertName"].Value;

【讨论】:

以上是关于c# Windows服务是不是(可能)使用app.config的主要内容,如果未能解决你的问题,请参考以下文章

C# Windows 服务 - 从 ini 或 App.config 文件中读取

Windows 服务配置文件 C#

如何使用 C# 中的 Windows 服务跟踪给定进程是不是引发异常

C#创建安装一个Windows服务

使用 C# 在 Windows 8 Metro App 上发送 POST 请求

如何使用 C# 找到 Windows 服务的安装目录?