I have a custom configuration file in my asp.net website, named urls.config, which contains simple key value, just for redirection purpose, now I want to read this file programmatically and also add values in this file, I am able to use XMLTextReader and XMLDocument to read value from this file, but i am unable to add values in this file.
Any help will be greatly appreciated.
Here is my structure for the configuration file:
<rewriteMaps>
<rewriteMap name="StaticRewrites" />
<add key="/superstars4012" value="/article.aspx?articleid=4012" />
<add key="/superstars4013" value="/article.aspx?articleid=4013" />
<add key="/superstars4014" value="/article.aspx?articleid=4014" />
<add key="/superstar" value="/article.aspx?articleid=4012" />
</rewriteMaps>
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("urls.config"));
XmlElement element = doc.CreateElement("add");
element.SetAttribute("key", txtAddVanity.Text);
element.SetAttribute("value", "/article.aspx?articleid=4012");
doc.DocumentElement.AppendChild(element);
doc.Save(Server.MapPath("urls.config"));
this works well if the file extension is .xml, but does not when i change it to .config, my requirement is .config, as redirects does not work in .xml
As eloquently stated in this msdn post, modifying the web.config file while the application is running is certainly possible (as it is just text, after all) but would be a very bad idea, in that modifying the config file will result in the application being restarted on the server — ending any sessions with current users, and all new visitors seeing an error page until the application is restarted. Certainly not ideal.
From the look of your code,
It appears you are doing url rewriting from a static url to a dynamic query string. There are much better ways of accomplishing this. One is the IIS module “user-friendly urls.” I have very few problems that I couldnt solve using this module.
Its logic is as follows:
This would be much easier to maintain, as well as safer for your application and your users.
-Cheers!