In this Article, I am going to discuss about how can we store custom objects i.e our own variables in
web.config. Generally we used to have some data in
appSettings section of web.config and read it when required in web forms. But actually we can not only read that data i code behind files for our web forms but we can update the data as well in web.config programmatically.
There are number of pre defined object which we can create in web.config. But the main point of this article is, storing some object of custom type in web.config. This can be very useful in a number of scenarios.
- First of all we have to create our own custom object in
appSettingssection of web.config which we will refer to in our web forms.
<add key="HowToIdeas" value="This is a simple message.." />
- To read its value in code file, add the following namespaces in your code file.
- Now use the following line of code to retrieve the value of the object we have created.
String s = ConfigurationManager.AppSettings["HowToIdeas"].ToString();
- Response.Write will write the string on our web page. Here is the output of these statements in my web page.
- Now to change the value of this object, use the following statement.
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
config.AppSettings.Settings["HowToIdeas"].Value = "This is the updated message..";
- So when this will run, it will change the value of our object in web.config. But this change will be reflected back the next time when the page will be reloaded. Actually this statement will change the actual value in web.config which will be saved after the page gets fully loaded and this value will be retrieved only after that.
- On my page when I click the second button (Original Message) the following output will be shown.
- After that when I click the 1st button (change value), I get the following output.
- In above screenshot the message shown on page is same as the previous one, but actually the value is changed and will be reflected back the next time. So when I click the third button (New Value), I get the following output.
- And when you stop the website, you will also get a message stating your web.config file has been updated from outside.
- Here is the snapshot of the whole code I am running on this page.
Incoming search terms:
- store data in web config (1)