开发者

Editing .config file in code

开发者 https://www.devze.com 2023-03-20 23:35 出处:网络
I\'m writing a program using WPF and C# that has an \"app.config\" file which stores the name and location of several servers. The program dynamically reads from this config file, and displays it(amon

I'm writing a program using WPF and C# that has an "app.config" file which stores the name and location of several servers. The program dynamically reads from this config file, and displays it(among other things) in a UI.

I'm trying to include a front end way to add new servers to the configuration file, so that the user can enter the properties of the server needed, and my program adds it to the config file.

My config file essentially looks something like this:

<ServerConfig>
<Environment name="PROD">
  <Server host="h1" share="s1" source="x1"/>
  <Server host="h6" share="s1" source="x1"/>
  <Server host="h7" share="s1" source="x1"/>
  <Server host="h8" share="s1" source="x1"/>
  <Server host="h155" share="s1" source="x1"/>
</Environment>
<Environment name="DEV">
  <Server host="h2" share="s2" source="x2"/>
  <Server host="h55" share="s1" source="x1"/>
  <Server host="h115" share="s1" source="x1"/>
</Environment>
<Environment name="QA">
  <Server host="h3" share="s3" sou开发者_如何学Gorce="x3"/>
  <Server host="h46" share="s1" source="x1"/>
  <Server host="h15" share="s1" source="x1"/>
  <Server host="h2" share="s1" source="x1"/>
  <Server host="h234" share="s1" source="x1"/>
  <Server host="h6" share="s1" source="x1"/>
  <Server host="h146" share="s1" source="x1"/>
</Environment>
</ServerConfig>

I want the user to be able to input a host, share, and source, and environment, and I need to find a way to place that line of Xml Code in the proper place.

Is there a way to search for a tag with a certain "name" (such as searching for the 'QA' environment) and adding the line after that? XmlWriter/XmlSerializer seems to be able to only write from the beginning of an Xml file, not comb through it before writing.

I appreciate any help.


I suggest creating custom objects that encapsulate this information (servers) and functionality (adding servers), then serializing those a an XML file separate from the web.config. This keeps your custom settings all in one place, and avoids meddling in the standard config file which I see as being useful for settings that are not changed at runtime. I've done this for one project and it works well.

0

精彩评论

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