Reputation: 15475
Trying to search web.config using ConfigurationElementCollection.
Here's the article source: https://www.iis.net/configreference/system.webserver/modules/add
Here's a snippet of c# code I'm trying to use:
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetWebConfiguration("Default Web Site/app1");
ConfigurationSection modulesSection = config.GetSection("system.webServer/modules");
ConfigurationElementCollection modulesCollection = modulesSection.GetCollection();
ConfigurationElement addElement = modulesCollection.CreateElement("remove");
addElement["name"] = @"CartHeader";
//addElement["type"] = @"Contoso.ShoppingCart.Header";
//addElement["preCondition"] = @"managedHandler";
// Check if your CartHeader module exists
var exists = modulesCollection.Any(m => m.Attributes["name"].Value.Equals("CartHeader"));
// Handle accordingly
if (!exists)
{
// Create your module here
modulesCollection.Add(addElement);
serverManager.CommitChanges();
}
}
How do I check to see if that element already exists before I add it?
I changed the CreateElement("remove") and I added a check before trying to add the element but apparently it doesn't take <remove>
elements into consideration because it keeps adding it. Am I missing something?
Upvotes: 0
Views: 511
Reputation: 76597
You could likely use a bit of LINQ to query and see if an element with that specific name attribute exists via the Enumerable.Any()
method :
// Check if your CartHeader module exists
var exists = modulesCollection.Any(m => m.Attributes["name"].Value.Equals("CartHeader"));
// Handle accordingly
if(!exist)
{
// Create your module here
}
Upvotes: 1