【问题标题】:Config file for c# windows servicec# windows服务的配置文件
【发布时间】:2013-06-05 17:31:44
【问题描述】:

我有这个配置文件:

   <?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 服务创建一个配置文件以在启动时读取,这是一个好方法,还有其他更好的方法吗?

【问题讨论】:

  • 您的 .config 文件的名称是什么?最后应该是服务可执行文件的名称+.config,所以MyWindowsService.exe应该是MyWindowsService.exe.config。它还应该与您的服务可执行文件位于同一目录中。您还需要重新启动 Windows 服务才能获取对文件的更改。
  • 你为什么不使用 ConfigurationManager.AppSettings?
  • @matt-dot-net 很好,为此 +1。
  • 你知道他们怎么说..@matt-dot-net:真实故事!

标签: c# windows windows-services


【解决方案1】:

首先您必须将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);
    } 
}

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多