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

7
我正在尝试编写一个Winform应用程序,可以编辑已安装Web应用程序的web.config文件。 我已经阅读了ConfigurationManager和WebConfigurationManager类的方法,但我不确定如何打开Web应用程序的配置文件并进行编辑。
我正在寻找一种不需要将配置文件作为常规XmlDocument加载的方法,尽管如果这是唯一可用的选项,我愿意这样做。
任何建议都将不胜感激。
4个回答

8

好的,这里是答案。我有完全相同的情况。我想编写一个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);

Here is an example of what it does

Before:

<?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从返回的配置对象中提取数据,最后它具有一个保存方法,用于写出数据。使用此类,我能够将类添加为数据源并将绑定控件拖放到Winform中。从那里,您只需连接调用类上的保存方法的按钮即可。

配置类

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设计器,选择Data > Show Data Sources (Shift+Alt+D)。右键点击 Add New Data Source,如下图所示将其添加为对象。

数据源配置向导 1/2 http://img109.imageshack.us/img109/8268/98868932.png

数据源配置向导 2/2 http://img714.imageshack.us/img714/7287/91962513.png

将其(WebConfigSettings,最上面一个)拖到winform上。在我的案例中,我会删除导航器,因为那是针对列表的,而我只有一个。

刚添加的绑定控件 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中添加一个保存按钮。

已添加保存按钮 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类,在Data Sources窗口中刷新数据源(构建后),然后将新字段拖放到UI上。

您仍然需要编写一些代码来指定要打开的web.config,对于此示例,我只是硬编码了路径。

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


我给你一个“点赞”。虽然你的帖子只是回答了问题。 - Abdul Munim

1

我强烈建议你使用启用了LINQ的(LINQ to XML)。

例如,如果您想要更改connectionString,则此类型的代码已足够好。

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

现在您可以完全控制<connectionString />元素,并对其进行任何想要的操作。

我向您推荐MSDN进行学习,以及Kick Start进行即时工作。

希望这能帮助您轻松地完全控制您的.xml


他明确表示他不想这样做。这里的每个人都知道 web.config 是 XML,你可以以任何你认为合适的方式打开和编辑它。 - Allen Rice
@Allen,ConfigurationManager类确实可以用于修改/添加。您还应该记住,ConfigurationManager类对AppSettingsConnectionStrings有控制权。XmlDocument很痛苦,而ConfigurationManager.config文件的解决方案之一。相信我,当您需要强大的功能时,LINQ to XML更加方便。顺便说一下,Allen,您应该知道自己的礼仪。您应该知道何时投票支持或反对。干杯 - Abdul Munim

0

这里有一个玩具应用程序(VB.NET Windows客户端),可以使用树/网格导航和编辑来编辑XML文件。

您可能会从中获得一些想法。如果您想在web.config上尝试它,可以在此处找到它的VS项目文件或者只是一个MSI安装程序此处

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


0
所有的 app.configweb.config 都是 XML 文件。您可以使用 XMLDocument、XMLWriter 等打开并编辑它们。

问题明确表示他们不想使用通用的XMLDocument对象(这是一个好主意,因为你不需要重新发明轮子)。 - Russell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接