如何根据app.config文件中的值获取密钥?

时间:2013-03-19 11:00:43

标签: c# asp.net

我有一个这样的app.config文件: -

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="botLogs" value="d:\TFS Projects-BotLogs/"/>
    <add key="botfolder" value="C:\BOTSCONFIG"/>
  </appSettings>
  <connectionStrings>
    <add connectionString="Server=1.1.1.1;Database=BGAppCrawling;UID=sa;Password=something;" name="VGDB"/>
    <add connectionString="Server=1.1.1.1;Database=BGMappingStaging;UID=sa;Password=something;" name="VGDBMapping"/>
  </connectionStrings>
</configuration>

现在我可以根据appSettings部分中的键获取值,如下所示: -

string filePath = ConfigurationSettings.AppSettings["botLogs"].ToString();

但是,如果我想根据appSetting部分的值获取密钥,该怎么办?

4 个答案:

答案 0 :(得分:0)

foreach(string key in System.Configuration.ConfigurationSettings.AppSettings)
{   
 var key = key.ToString();   
 var value = ConfigurationSettings.AppSettings[key.ToString()];
 //Do something here
}

var settings = System.Web.Configuration.ConfigurationSettings.AppSettings;

var value = from string k in settings.Keys
            where k.StartsWith("MyValue")
            select settings[k];

答案 1 :(得分:0)

您可以尝试使用基于GetEnumerator method的代码:

NameValueCollection values = ConfigurationManager.AppSettings;
Iterate(values);    
public void Iterate(NameValueCollection myCollection)
{
    IEnumerator myEnumerator = myCollection.GetEnumerator();
    Console.WriteLine("KEY VALUE");
    foreach (String item in myCollection.AllKeys)
    Console.WriteLine(" {0,-10} {1}", item, myCollection[item]);
    Console.WriteLine();
}

答案 2 :(得分:0)

 foreach (string key in Configuration.AppSettings.Settings.AllKeys)
        {
            string value = appSettings.Settings[key].Value;

            if (value.Equals(myValue))
            {
                 Console.WriteLine("Found Key: " + key);
                 break;
            }
        }

答案 3 :(得分:0)

我会说你应该用值替换你的键,用键替换值,

<add  key="d:\TFS Projects-BotLogs/" value="botLogs"/>
<add  key="C:\BOTSCONFIG" value="botfolder"/>  

感谢 勒凯什