2012-03-10 4 views
1

사용자 지정 구성 설정이 있습니다.web.config에서 xml 요소 목록 가져 오기

public class GalleryResizeOptionsElement : ConfigurationElement 
{ 
    [ConfigurationProperty("name")] 
    public string Name 
    { 
     get { return (string)this["name"]; } 
    } 

    [ConfigurationProperty("width")] 
    public int Width 
    { 
     get { return (int)this["width"]; } 
    } 

    [ConfigurationProperty("height")] 
    public int Height 
    { 
     get { return (int)this["height"]; } 
    } 
} 

public class GalleryResizeOptionsCollection : ConfigurationElementCollection 
{ 
    protected override ConfigurationElement CreateNewElement() 
    { 
     return new GalleryResizeOptionsElement(); 
    } 

    protected override object GetElementKey(ConfigurationElement element) 
    { 
     return ((GalleryResizeOptionsElement)element).Name; 
    } 


    public override ConfigurationElementCollectionType CollectionType 
    { 
     get { return ConfigurationElementCollectionType.BasicMap; } 
    } 

    /// <summary> 
    /// The element name of the configuration elements in the config file, 
    /// as set at UserCommandConfigurationConstants.ElementName 
    /// </summary> 
    protected override string ElementName 
    { 
     get { return "add"; } 
    } 

    /// <summary> 
    /// This is a convenience added to allow selection from the collection 
    /// via the commandkey as an index 
    /// </summary> 
    /// <returns></returns> 
    public GalleryResizeOptionsElement this[string name] 
    { 
     get { return (GalleryResizeOptionsElement)this.BaseGet(name); } 
    } 
} 

public class GalleryConfigurationSection : ConfigurationSection 
{ 

    public virtual GalleryResizeOptionsCollection ResizeOptions 
    { 
     get { return (GalleryResizeOptionsCollection) base["resizeOptions"]; } 
    } 
} 

web.config 파일에이 xml 구성을 포함하는 섹션이 추가됩니다.

<resizeOptions> 
     <add name="Square" width="100" height="100" /> 
     <add name="Rectangle" width="200" height="100" /> 
     <add name="Hero" width="600" height="400" /> 
     </resizeOptions> 

나는 간결함을 위해 밖으로 다른 코드를 많이 떠 났어요,하지만 난 내 질문을하는 데 필요한 모든 것을 포함 것 같아요.

GalleryResizeOptionsCollection을 어떻게 변경하여 모든 GalleryResizeOptionsElements의 목록을 반환 할 수 있습니까? 또는 명확한 용어로 모든 "추가"요소의 목록을 반환 할 수 있기를 원합니다.

+0

볼 http://stackoverflow.com/questions/2260317/change-a-web-config-programmatically-with-c-sharp-을 net 및 http://stackoverflow.com/questions/4357238/is-there-a-way-to-programmatically-save-values-to-web-config-appsettings- 희망이 있으면 도움이 될 것입니다. –

답변

0

당신은 요소의 목록을 반환하는 System.Linq를 사용할 수 있습니다

using System.Linq; 

public class GalleryResizeOptionsCollection : ConfigurationElementCollection 
{ 
    //... 

    public IList<GalleryResizeOptionsElement> ToList() 
    { 
     return this.Cast<GalleryResizeOptionsElement>().ToList(); 
    } 
}