如何编辑外部web.config文件?

时间:2009-08-19 14:40:41

标签: winforms configuration web-config

我正在尝试编写一个winform应用程序,该应用程序可以编辑已安装的Web应用程序的web.config文件。 我已经阅读了ConfigurationManager和WebConfigurationManager类方法,但我不确定如何打开Web应用程序的配置文件并进行编辑。

我正在寻找一种方法,它不需要我将配置文件作为常规XmlDocument加载,但如果这是唯一可用的选项,我愿意这样做。

任何建议都将受到赞赏。

4 个答案:

答案 0 :(得分:7)

好的,这就是答案,我有完全相同的情况。我想编写一个winforms应用程序,以允许普通用户更新web.config。你必须让配置变得愚蠢...

// the key of the setting
string key = "MyKey";

// the new value you want to change the setting to
string value = "This is my New Value!";

// the path to the web.config
string path = @"C:\web.config";

// open your web.config, so far this is the ONLY way i've found to do this without it wanting a virtual directory or some nonsense
// even "OpenExeConfiguration" will not work
var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None);

// now that we have our config, grab the element out of the settings
var element = config.AppSettings.Settings[key];

// it may be null if its not there already
if (element == null)
{
 // we'll handle it not being there by adding it with the new value
 config.AppSettings.Settings.Add(key, value);
}
else
{
 // note: if you wanted to you could inspect the current value via element.Value

 // in this case, its already present, just update the value
 element.Value = value;
}

// save the config, minimal is key here if you dont want huge web.config bloat
config.Save(ConfigurationSaveMode.Minimal, true);

这是一个例子

在:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="MyKey" value="OldValue" />
  </appSettings>
  <connectionStrings>
    <add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

后:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="MyKey" value="This is my New Value!" />
  </appSettings>
  <connectionStrings>
    <add name="myConnString" connectionString="blah blah blah" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <trust level="Full" />
    <webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
  </system.web>
</configuration>

请注意,如果你给它一个无效的路径,它只会在该路径/文件名创建一个配置文件。基本上,首先要对File.Exists进行检查

顺便说一句,当你在它的时候,你可以在web.config中编写一个代表你的设置的类。执行此操作后,编写getter / setter以读取/写入web.config中的设置。完成此操作后,您可以将此类添加为数据源,并将数据绑定控件拖到您的winform上。这将为您提供一个完全数据绑定的winform web.config编辑器,您可以在几分钟内轻松完成。 我在工作中有一个明天发布的例子。

功能齐全的winforms解决方案

所以这是编写一个Gui来编辑web.config的一个相对简单的解决方案,有些人可能会说,当记事本做得很好时它过于复杂但它适用于我和我的观众。

它基本上如上所述,我编写了一个具有我想要的配置点作为属性的类。 ctor从路径打开文件,getter / setter从返回的配置对象中提取数据,最后它有一个将其写出的save方法。通过这个类,我可以将类添加为数据源,并将绑定控件拖放到winforms上。从那里你要做的就是连接一个在你班上调用save方法的按钮。

配置类

using System.Configuration;

// This is a representation of our web.config, we can change the properties and call save to save them
public class WebConfigSettings
{
 // This holds our configuration element so we dont have to reopen the file constantly
 private Configuration config;

 // given a path to a web.config, this ctor will init the class and open the config file so it can map the getters / setters to the values in the config
 public WebConfigSettings(string path)
 {
  // open the config via a method that we wrote, since we'll be opening it in more than 1 location
  this.config = this.OpenConfig(path);
 }

 // Read/Write property that maps to a web.config setting
 public string MySetting
 {
  get { return this.Get("MySetting"); }
  set { this.Set("MySetting", value); }
 }

 // Read/Write property that maps to a web.config setting
 public string MySetting2
 {
  get { return this.Get("MySetting2"); }
  set { this.Set("MySetting2", value); }
 }

 // helper method to get the value of a given key
 private string Get(string key)
 { 
  var element = config.AppSettings.Settings[key];

  // it may be null if its not there already
  if (element == null)
  {
   // we'll handle it not being there by adding it with the new value
   config.AppSettings.Settings.Add(key, "");

   // pull the element again so we can set it below
   element = config.AppSettings.Settings[key];
  }
  return element.Value;
 }

 // helper method to set the value of a given key
 private void Set(string key, string value)
 {
  // now that we have our config, grab the element out of the settings
  var element = this.config.AppSettings.Settings[key];

  // it may be null if its not there already
  if (element == null)
  {
   // we'll handle it not being there by adding it with the new value
   config.AppSettings.Settings.Add(key, value);
  }
  else
  {
   // in this case, its already present, just update the value
   element.Value = value;
  }
 }

 // Writes all the values to the config file
 public void Save()
 {
  // save the config, minimal is key here if you dont want huge web.config bloat
  this.config.Save(ConfigurationSaveMode.Minimal, true);
 }

 public void SaveAs(string newPath)
 {
  this.config.SaveAs(path, ConfigurationSaveMode.Minimal, true);

  // due to some weird .net issue, you have to null the config out after you SaveAs it because next time you try to save, it will error
  this.config = null;
  this.config = this.OpenConfig(newPath);
 }

 // where the magic happens, we'll open the config here     
 protected Configuration OpenConfig(string path)
 {
  return ConfigurationManager.OpenMappedExeConfiguration(
        new ExeConfigurationFileMap() {  ExeConfigFilename = path }, 
        ConfigurationUserLevel.None);   
 }
}

构建然后从那里你可以转到你的winform设计师,转到数据&gt;显示数据源(Shift + Alt + D)。右键单击&gt;添加新数据源并将其添加为对象,如图所示

Data Source Configuration Wizard 1 of 2 http://img109.imageshack.us/img109/8268/98868932.png

Data Source Configuration Wizard 2 of 2 http://img714.imageshack.us/img714/7287/91962513.png

将它(WebConfigSettings,最顶层)拖到winform上。在我的情况下,我将删除导航器,因为它是一个List,我只有一个。

Freshly added databound controls http://img96.imageshack.us/img96/8268/29648681.png

你应该在设计师的底部有类似webConfigSettingsBindingSource的东西(如下图所示)。转到代码视图并将ctor更改为此

public Form1()
{
    InitializeComponent();

    // wire up the actual source of data
    this.webConfigSettingsBindingSource.DataSource = new WebConfigSettings(@"c:\web.config");
}

为winform添加保存按钮

Save button added http://img402.imageshack.us/img402/8634/73975062.png

添加以下事件处理程序

private void saveButton_Click(object sender, EventArgs e)
{
    // get our WebConfigSettings object out of the datasource to do some save'n
    var settings = (WebConfigSettings)this.webConfigSettingsBindingSource.DataSource;

    // call save, this will write the changes to the file via the ConfigurationManager
    settings.Save();
}

在那里,现在你有一个很好的简单的数据绑定web.config编辑器。要添加/删除字段,只需修改WebConfigSettings类,在“数据源”窗口中刷新数据源(在构建之后),然后将新字段拖放到UI上。

你仍然需要连接一些指定要打开的web.config的代码,对于这个例子,我只是对路径进行了硬编码。

这里很酷的是GUI添加的所有价值。您可以轻松添加目录或文件浏览器对话框,您可以拥有连接字符串测试器等。所有这些都非常容易添加,并且对最终用户来说非常强大。

答案 1 :(得分:1)

我强烈建议您使用XElement以及启用LINQ(LINQ to XML)。

例如,您想要更改connectionString。这种类型的代码足够好

var connString = from c in webConfigXElement.appSettings.connectionString
                        where c.name == "myConnection"
                        select c;

现在您可以完全控制<connectionString />元素,并执行任何操作。

我指的是MSDN用于学习,还有Kick Start用于即时工作。

希望这可以帮助您完全控制.xml而不会感到痛苦。

答案 2 :(得分:0)

在这里,我写了一个玩具应用程序(VB.NET Windows客户端),它使用树/网格编辑XML文件进行导航和编辑。

您可能会从中获得一些想法。如果你想在你的web.config上试用它,那么它的VS项目文件是here或只是安装它的MSI是here

将文件加载到DataSet(DataSet.ReadXML())中,DataSet将其解析为DataTables,然后显示并允许编辑标准DataGrid中的内容。然后它将编辑的内容保存回XML文件(DataSet.WriteXML())。

答案 3 :(得分:-1)

所有app.configweb.config都只是XML文件。您可以使用XMLDocument,XMLWriter等打开和编辑它们。

相关问题