By external config files, I mean .config files other than web.config. I've seen all the examples on how to edit web.config at runtime, but I want to edit a config file referenced by a configSource for appSettings. I want to modify only the external file and I will handle the app recycle.
Ideally I would like to use a built-in class to deal with the edits, but if the only option is a manual File open/parse, etc, then sobeit.
The general idea behind all this being a Settings page that is viewed at app startup, user sets their particulars and then saves the changes, then the real app starts up. quick and easy install app/configure page, so I'd like to leverage .config if at all possible.
Thanks!
FOLLOWUP - Quick Snippet to use XmlDocument to change an appSetting key value:
string path = Server.MapPath("~/my.config");
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode node = doc.SelectSingleNode("/appSettings/add[@key='myKey']");
node.Attributes[1].Value = "myVal";
XmlTextWriter writer = new XmlTextWriter(path, null);
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
writer.Flush();
writer.Close();
the answer i found :- ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.
We can definitely modify the web. config at runtime but it would restart the Application again. Hence we recommand to call the value from XML or Resource File which will not alter the Application. Consider, we are fetching the above given Appsettings value.
config (or any file) when you press F5 in Visual Studio. You can have different transformations based on the build configuration. This will enable you to easily have different app settings, connection strings, etc for Debug versus Release. If you want to transform other files you can do that too.
The usual code for editing standard configuration files goes like this:
string cfgPath = Path.Combine(targetDir, "myApp.config");
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = cfgPath };
var cf = ConfigurationManager.OpenMappedExeConfiguration(configMap,
ConfigurationUserLevel.None);
cf.AppSettings.Settings["somekey"].Value = "newvalue";
cf.Save();
Code version is .NET 3.5, by the way.
You probably need to set the correct permissions as well. Note that if you don't have the standard configuration file layout (root node is <configuration>
) this code will throw an exception.
You should, at the very least, be able to utilize the classes in the System.Xml Namespace to read the settings files as any old XML file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With