c# - c# windows服务的配置文件

标签 c# windows windows-services

我有这个配置文件:

   <?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="AuxAppStg0" value="5 iunie 2013 19:22:49" />
        <add key="AuxAppStg1" value="5 iunie 2013 00:00:00" />
        <add key="AppStg2" value="5 iunie 2013 19:23:04" />
    </appSettings>
</configuration>

我想用这段代码解析它:

 // Get the configuration file.
        System.Configuration.Configuration config =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        // Get the appSettings section.
        System.Configuration.AppSettingsSection appSettings =
            (System.Configuration.AppSettingsSection)config.GetSection("appSettings");



        foreach (KeyValueConfigurationElement i in appSettings.Settings)
        {

            Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value);
        }

        if (appSettings.Settings.Count != 0)
        {
            foreach (string key in appSettings.Settings.AllKeys)
            {
                string value = appSettings.Settings[key].Value;
                Console.WriteLine("Key: {0} Value: {1}", key, value);
            }
        }
        else
        {
            Console.WriteLine("The appSettings section is empty. Write first.");
        }

我得到的只是:appSettings 部分是空的。先写。 我找到了here .我做错了什么?我想为 c# windows 服务创建一个配置文件以在启动时读取,这是一个好方法吗,还有其他更好的方法吗?

最佳答案

首先,您必须将 System.configuration 引用导入到您的项目中。

然后你可以使用这样的东西:

private void ParseAppSettings() {
    string value = string.Empty;
    foreach (string key in System.Configuration.ConfigurationManager.AppSettings.AllKeys)
    {
        value = System.Configuration.ConfigurationManager.AppSettings[key];
        Console.WriteLine("Key: {0} Value: {1}", key, value);
    } 
}

关于c# - c# windows服务的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16946287/

相关文章:

c# - MouseDown/MouseLeftButtonDown 事件未触发,MouseUp 是?

c# - Invoke 流不支持读取

windows - 如何调试在引导时启动的进程?

c++ - 来自 MSDN 的 InternetGetConnectedState 和 "it should not be used from a service"语句

c# - 使用 anchor 指向谷歌地图上的位置

c# - NHibernate 的 T4 模板? - 不流利的 NHibernate

c# - 如何获取当前 Windows 帐户的 SID?

windows - 如何确定为磁盘设备分配了哪些 block ?

c# - 无法加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching”

c# - 在Windows服务中使用计时器