I checked a lotArticleThe following methods are used to modify the values in APP. config:
Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. None );
Config. etettings. settings ["db_uid"]. value = "Demo ";
Config. Save (configurationsavemode. Full );
It turns out that this approach is not feasible. AlthoughProgramThe runtime value has been modified. However, when you open app. config to view it, the value is still not changed. If the program is restarted, the old value is used. This method can only read values. Values cannot be written or modified.
The correct method is to treat app. config as a common XML file and modify it.
Xmldocument xdoc = new xmldocument ();
Xdoc. Load (system. Windows. Forms. application. executablepath + ". config ");
Xmlnode xnode;
Xmlelement xelemuid;
Xnode = xdoc. selectsinglenode ("// appsettings ");
Xelemuid = (xmlelement) xnode. selectsinglenode ("// Add [@ key = 'db _ uid']");
Xelemuid. setattribute ("value", encrypt. Create (). encryptdata (this. dbusertxt. Text ));
Xdoc. Save (system. Windows. Forms. application. executablepath + ". config ");
Private void updateconfig (string xvalue)
{
Xmldocument Doc = new xmldocument ();
Doc. Load (appconfig ());
Xmlnode node = Doc. selectsinglenode (@ "// appsettings ");
Xmlelement ele = (xmlelement) node. selectsinglenode (@ "// Add [@ key = 'birelease']");
Ele. setattribute ("value", application. startuppath );
Doc. Save (appconfig ());
}
Public String appconfig ()
{
Int intpos = application. startuppath. Trim (). indexof ("bin")-1;
String strdirectorypath = system. Io. Path. Combine (application. startuppath. substring (0, intpos), "app. config ");
Return strdirectorypath;
}
Public String getvalue (string appkey)
{
Xmldocument xdoc = new xmldocument ();
Try
{
Xdoc. Load (appconfig ());
Xmlnode xnode;
Xmlelement xelem;
Xnode = xdoc. selectsinglenode ("// appsettings"); // Add it to your app. config file. <appsetting> </appsetting>
Xelem = (xmlelement) xnode. selectsinglenode ("// Add [@ key = '" + appkey + "']");
If (xelem! = NULL)
Return xelem. getattribute ("value ");
Else
Return "";
}
Catch (exception)
{
Return "";
}
}