开发者

Modifying a web.config file as if it was a text file

I need to add many entries to my web.config file开发者_StackOverflow社区 for many websites.

I started by looking at using the XmlDocument and creating elements and attributes and then inserting them into the document. Pretty soon this looked like a massive amount of work for all the elements I have to add.

What are the repercussions of treating the config file as one big long text string and doing a replace at certain points to add my entries. Something like this…

private void InsertXMLElement()
{
    StringBuilder webConfig = new StringBuilder();

    // get the file into a stringbuilder for manipulation
    using (var sr = new StreamReader("C:\web.config"))
    {
        webConfig.Append(sr.ReadToEnd());
    }

    // insert my element by doing a replace
    webConfig.Replace("</configSections>","very long xml element with lots of attributes" + "</configSections>");

}

Obviously I know the state of the file before hand or could perform additional checks to make sure the entries do not already exist.


It's best to avoid re-inventing the wheel whenever possible.

Have you looked at the ConfigurationManager? It's really useful. It has a lot of good methods, such as GetSection.

Once you have the relevant section, you can save the amendments.


The worst case I can think of given your scenario is that your replacement text contains a <!-- ... --> comment and the file contains </configSections> already inside a comment, since xml comments don't nest well. If you assert that your "very long xml..." has no comments it'll probably work (although the result may not always be pretty).

Personally I'd use xml...


I'd have to agree with Joe R and Marc, that using XML if you are just adding attributes is the way to go.

That said, I do exactly what you are stating (for another purpose) without harm.

We wanted a way to allow developers to keep a single copy of the QA/Test web.config checked in w/o having to know which of our 10 test systems (all dns hard-named for access by multiple teams) the code was deploying to. So the developers check in web.configs with variables and a control character "$(x)" and we parse as text and replace at deploy time. I found I had more flexibility and better performance (I break the file apart, parallel process in blocks/lines, then reassemble)

So to answer, technically it shouldn't be a problem.

To suggest, don't do it unless you find some specific reason to do this. I would never have done this w/o trying the XML approach first, having success, and just wanting different behavior

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜