How to loop through web.config list

Below code shows how to loop through the web.config list.

Here i used the example of user list. This code can be used if you want to store user names and password in web.config file and wanted to verify the same while user logs in the application.

You can call this function on click of the LOGIN button.

In web.config add user list like below, Key is the userid and value is your password


<UserList>
<add key="Admin" value="Admin" />
<add key="Superuser" value="Superuser" />
<add key="User" value="User" />
<add key="Guest" value="Guest" />
</UserList>


Then you have to add for the UserList in web.config,



<configSections>
<section name="UserList" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>



Now we will move to C# coding section,

Create a boolean function whihc can be called on click of the login button.

Pass two parameters as userid and password

private bool IsValidUser(string strUserId, string strPwd)
{
//declare a variable to return false if there is no match found
bool isValid = false;

//Declare a name value collection to store UserList from web.config
NameValueCollection nvcUserList;
nvcUserList = (NameValueCollection)ConfigurationSettings.GetConfig("UserList");

//Loop through the collection
for (int i = 0; i < nvcUserList.Count; i++)
{
//Get Key name into a string
string strUserIDFromList = nvcUserList.Keys[i].ToString();
//Get Key value into a string
string strPwdFromList = nvcUserList.Get(i);

//Check if both userid and password entered is correct, if yes return true else return false
if (strUserIDFromList.Trim().ToUpper() == strUserId.Trim().ToUpper() && strPwdFromList.Trim().ToUpper() == strPwd.Trim().ToUpper())
{
return true;
}
}
return isValid;
}


Comments

Author: Asheej T K22 Nov 2009 Member Level: Gold   Points : 1

I have formatted the code, but when i paste it here all formatting disappeard. If this is not the one you are expecting please let me know if there is any other way to format the code.

Author: ABitSmart22 Nov 2009 Member Level: Gold   Points : 1

Take a look at how I have formatted the HTML. Edit the other one and resubmit. I will approve it.

Author: Asheej T K22 Nov 2009 Member Level: Gold   Points : 0

I hope now it looks better...



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: