2016-07-08 11 views
0

ConfigurationElementCollectionを使用してweb.configを検索しようとしています。追加する前にその要素が既に存在するかどうかを確認するにはどうすればよいですか?

ここで記事の源です: https://www.iis.net/configreference/system.webserver/modules/add

は、ここで私が使用しようとしているC#のコードの抜粋です:

 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(); 
      } 
     } 

私はそれを追加する前に、どのように私はその要素が既に存在するかどうかをチェックしますか?

私はCreateElement( "remove")を変更し、要素を追加しようとする前にチェックを追加しましたが、明らかに要素を追加し続けるので、<remove>要素を考慮しません。何か不足していますか?

+0

あなたはモジュールのコレクションをループする必要があるし、何で要素を比較あなたは追加したい。 – Kami

答えて

1

あなたはおそらくその特定のname属性を持つ要素がEnumerable.Any()メソッドを介して存在するかどうか照会し、確認するためにLINQのビットを使用することができます:

// 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 
} 
+0

明らかに、検索でが見つかりません。 Rod

+0

あなたの提案でOPが更新された場合、検索は正常に機能します。 – Rod

関連する問題