Reputation: 16282
here is my custom section in web.config. now i want read data by c#
<configuration>
<MailList>
<MailID id="[email protected]" Value="UK" />
<MailID id="[email protected]" Value="US" />
<MailID id="[email protected]" Value="CA" />
</databases>
</configuration>
suppose i want technique by which i can only read data based on value. if i supply UK as value then function will return uk mail id [email protected]
.
guide me how easily i can do this writing very minimum code. thanks
Upvotes: 0
Views: 310
Reputation: 7931
First of all your XML seems to be broken:
It must be something like that:
<configuration>
<MailList>
<MailID id="[email protected]" Value="UK" />
<MailID id="[email protected]" Value="US" />
<MailID id="[email protected]" Value="CA" />
</MailList>
</configuration>
This code should do what you want:
string country = "UK";
var result =
XDocument.Load("~/web.config")
.Element("configuration")
.Element("MailList")
.Elements("MailID")
.First(el => el.Attribute("Value").Value.Equals(country))
.Attribute("id")
.Value;
Console.WriteLine(result);
Upvotes: 1
Reputation: 1826
You could use the appsettings tag in your webconfig like:
<configuration>
<appSettings>
<add key="[email protected]" value="UK" />
<add key="[email protected]" value="US" />
<add key="[email protected]" value="CA" />
And after that you have your class:
public class WebConfigreader
{
public static string AppSettingsKey(string key)
{
if (WebConfigurationManager.AppSettings != null)
{
object xSetting = WebConfigurationManager.AppSettings[key];
if (xSetting != null)
{
return (string)xSetting;
}
}
return "";
}
}
And in your logic you are calling just:
String strUk = WebConfigreader.AppSettingsKey("[email protected]");
Upvotes: 1