问题
My project contains web.config file and an external appSettings file. I am making a WebConfig Editor that has options to Read AppSettings key from web.config and external appSetting file to display them on webPage. Also, I am allowing user to delete any key by clicking on Remove button. Moreover, user can also update any key's value by clicking on update button.Or he can also insert new key by clicking on Add New Key button.
The key issue I am facing is that whenfever I try to add a new key , it gets inserted into web.config file as expected , but at the same time it adds all the keys present in external appSettings file into web.config ( which is abrupt behavior).
How to stop this migration of keys from external appSettings file to web.config on any key's update / delete/ add function?
回答1:
For reading, put external file in Config folder under root and then use this code to read key/values based on key name it read from web.config or external file.
// get from web.config
String myKey = ConfigurationManager.AppSettings.Get("Key1");
String str += "AppSetting value from web.config:" + myKey;
// get from external AppSetting file
myKey = ConfigurationManager.AppSettings.Get("Key2");
String str2 += "AppSetting value from external AppSetting file:" + myKey;
where Key1 is in web.config and Key2 in external config file
also
to find al key values use foreach
loop
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
回答2:
While reading the keys add a unique signature with the keys of web.config file and external app settings file. on web only show keys not the signature, and when u add keys add the same signature ( if adding for web.config then web.config's Signature ) and when writing to the web.config apply the check for signature if the signature for the key is of external app settings file then ignore the key otherwise write the key.
Its the Simple solution, well if u have any query do ask
来源:https://stackoverflow.com/questions/5164439/reading-and-writing-keys-to-appsettings-in-webconfigeditor