【问题标题】:.NET ConfigurationElementCollection.Add method does not add item to collection.NET ConfigurationElementCollection.Add 方法不会将项目添加到集合
【发布时间】:2011-12-09 07:19:43
【问题描述】:

我有一个在 ASP.NET 4.0 下运行的自定义配置部分,我想保存更改。涉及的类有:

  • QueueConfiguration:一个配置元素
    • QueueCollection Queues // 要维护的队列列表
  • QueueCollection:一个 ConfigurationElementCollection
  • 队列:配置元素

这行得通:

// This is a test case to ensure the basics work
Queue newQueue = new Queue();
QueueCollection queues = new QueueCollection();
queues.Add(newQueue); // queues.Count is incremented here

这不起作用(并且不会引发错误):

// Read existing QueueConfiguration
Queue newQueue = new Queue();
QueueConfiguration queueConfig = ConfigurationManager.GetSection("Queuing") as QueueConfiguration;
queueConfig.Queues.Add(newQueue); // queues.Count is NOT incremented here

这也不起作用(并且不会引发错误):

// Load QueueConfiguration from web.config
Queue newQueue = new Queue();
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
QueueConfiguration queueConfig = config.GetSection("Queuing") as QueueConfiguration;
queueConfig.Queues.Add(newQueue); // queues.Count is NOT incremented here    

我的第一反应是三个配置部分中的一个被标记为只读。但是,当我调试时,IsReadOnly() 方法为我的 QueueConfiguration 和我的 QueueCollection 实例返回 false。

我的 QueueCollection 类包括这个 sn-p:

public void Add(Queue queue)
{
  base.BaseAdd(queue, true);
}

当我单步执行代码时,到达了这一行,调用了 base.BaseAdd,但 Count 属性没有递增。就好像 BaseAdd 只是忽略了请求。

有什么建议吗? (我希望我遗漏了一些明显的东西!)

【问题讨论】:

  • 您是否尝试在您的站点中实时编辑配置文件?
  • 这是我的最终目标,我通过其他配置部分成功地做到了这一点。但是,如果无法在保存之前将队列添加到我的 QueueCollection,则保存毫无意义。

标签: asp.net webconfigurationmanager configurationelement


【解决方案1】:

您是否在将时间添加到队列后调用了 Config.Save()。

Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

//Do work

config.Save();

【讨论】:

  • 是的,我做到了。配置保存到 .config 文件中,而没有我尝试添加到集合中的队列。我知道 .config 文件已更改,因为 XML 的格式已由 config.Save() 方法更改。但是,我认为到达 config.Save() 与我的问题无关。如果调用 Queues.Add() 实际上并没有添加队列(或抛出错误),那么保存配置是没有意义的。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多