Many times, we may dynamically modify the configuration file in the ASP.net, we can complete the configuration file using the classes involved in the following code, the following code is an example of modifying ConnectionString:
System.Configuration.Configuration C = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~") ;
C.connectionstrings.connectionstrings.clear ();
connectionstringsettings s = new connectionstringsettings ();
S.providername = "System.Data.OleDb";
s.connectionstring = "Provider=microsoft.oledb.jet.4.0;data Source=c://abc.mdb";
S.name = "Myaccess";
C.connectionstrings.connectionstrings.add (s);
C.save ();
Instance:
Web.config
--------------------
<configuration>
<appSettings>
<add key= "MyInt" value= "1234"/>
<add key= "LogFolder" value= "D:/workspace/javascript/slicing/slicingweb/log"/>
</appSettings>
</configuration>
----------------------
protected void Page_Load (object sender, EventArgs e)
{
Formsave ();
Websaveconfig ();
}
<summary>
You must specify ExePath when you are not running inside a standalone EXE
Openexeconfiguration (Configurationuserlevel.none) for the WinForm program
</summary>
public void Formsave ()
{
Configuration appcfg = configurationmanager.openexeconfiguration (
Configurationuserlevel.none);//?
Appsettingssection appSettings = appcfg.appsettings;
int myInt;
if (int. TryParse (appsettings.settings["MyInt"). Value, out MyInt))
{
Response.Write (MYINT);
MyInt *= 10;
appsettings.settings["MyInt"]. Value = Myint.tostring ();
Appcfg.save ();
Response.Write ("</br>" + myInt);
}
}
<summary>
asp.net in the web
</summary>
public void Websaveconfig ()
{
String path = Server.MapPath ("~/web.config");
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~");
Config. ConnectionStrings.ConnectionStrings.Clear ();
Appsettingssection appSettings = config. AppSettings;
int myInt;
if (int. TryParse (appsettings.settings["MyInt"). Value, out MyInt))
{
Response.Write (MYINT);
MyInt *= 10;
appsettings.settings["MyInt"]. Value = Myint.tostring ();
Config. Save ();
Response.Write ("</br>" + myInt);
}
}
------------------
Configuration file changes after execution
Web.config
--------------------
<configuration>
<appSettings>
<add key= "MyInt" value= "1234"/>
<add key= "LogFolder" value= "D:/workspace/javascript/slicing/slicingweb/log"/>
</appSettings>
</configuration>
----------------------