如何编辑外部web.config文件? [英] How to edit an external web.config file?

查看:141
本文介绍了如何编辑外部web.config文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个能够编辑已安装的Web应用程序的web.config文件的winform应用程序。
我已经阅读过ConfigurationManager和WebConfigurationManager类方法,但我不确定如何打开一个Web应用程序的配置文件并进行编辑。

I am trying to write a winform application that would be able to edit the web.config file of an installed web application. I have read through the ConfigurationManager and WebConfigurationManager class methods but I am unsure as to how I can open the configuration file of a web app and edit it.

我正在寻找一个方法,不要求我加载配置文件作为一个常规的XmlDocument,虽然我愿意这样做,如果这是唯一的选择可用。

I am looking for a method that does not require me to load the config file as a regular XmlDocument, although I am willing to do that if that is the only option available.

推荐答案

好的,这里是答案,我有EXACT同样的情况。我想写一个winforms应用程序,以允许普通用户更新web.config。你必须去获得配置一个愚蠢的方式...

Ok so here is the answer, I have the EXACT same scenario. I wanted to write a winforms app to allow normal users to update the web.config. You have to go about getting the config a goofy way...

// 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检查它

Just be careful, if you give it an invalid path, it will just create a config file at that path / filename. Basically, do a File.Exists check on it first

BTW,当你在它,你可以写一个类,代表你的web.config中的设置。一旦你这样做,写你的getters / setters读/写web.config中的设置。一旦THIS完成,您可以添加这个类作为数据源,并将数据绑定控件拖动到您的winform。这将给你一个完全数据绑定winform web.config编辑器,你可以轻松地敲出几分钟。

BTW, while you're at it, you could write a class that represents your settings in your web.config. Once you do this, write your getters/setters to read/write the settings in the web.config. Once THIS is done, you can add this class as a datasource and drag the databound controls onto your winform. This will give you a completely databound winform web.config editor that you can easily hammer out in a matter of minutes. I've got an example at work that I'll post tomorrow.

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

So this is a relatively simple solution to writing a Gui to edit a web.config, some may say its overly complicated when notepad will do just fine but it works for me and my audience.

它基本上如上所述工作,我写了一个类,它有我想要的配置点作为属性。 ctor 从路径中打开文件,getters / setter从返回的配置对象中拉出数据,最后它有一个保存方法。使用这个类,我可以添加类作为数据源和拖放绑定控件到winforms。

It basically works as described above, I wrote a class that had the configuration points that I wanted as properties. The ctor opens the file from a path and the getters / setters pull the data out of the returned configuration object, finally it has a save method that writes it out. With this class, I'm able to add the class as a datasource and drag / drop bound controls onto winforms. From there all you have to do is to wire up a button that calls the save method on your class.

配置类

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设计器,goto数据>显示数据源(Shift + Alt + D)。右键单击>添加新数据源并将其添加为对象,如下所示

Build and then from there you can just goto your winform designer, goto Data > Show Data Sources (Shift+Alt+D). Right click > Add New Data Source and add it as an object as shown

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

Drag it (WebConfigSettings, the topmost) onto the winform. In my case, I will remove the navigator as that is for a List and I just have one.

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

You should have something like webConfigSettingsBindingSource at the bottom of the designer (shown in the next pic). Goto the code view and change the ctor to this

public Form1()
{
    InitializeComponent();

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

向您的winform添加保存按钮

Add a save button to your winform

添加以下事件处理程序

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类,刷新数据源窗口中的数据源(构建之后),然后拖动n将新字段拖放到UI上。

There, now you have a nice simple databound web.config editor. To add / remove fields, you just modify your WebConfigSettings class, refresh the datasource in the Data Sources window (after a build), and then drag n drop the new fields onto the UI.

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

You'll still have to wire up some code that specifies a web.config to open, for this example I just hard coded the path.

这里的东西是GUI增加的所有价值。你可以轻松地添加目录或文件浏览器对话框,你可以有连接字符串测试器等。所有是很容易添加和非常强大的最终用户。

The cool thing here is all the value that a GUI adds. You can easily add directory or filebrowser dialogs, you can have connection string testers etc. All are very easy to add and very powerful to the end user.

这篇关于如何编辑外部web.config文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆