Не удается сохранить коллекцию пользовательских настроек в пользовательском разделе - PullRequest
0 голосов
/ 01 мая 2019

У меня проблема с сохранением коллекции в пользовательский раздел в файле app.config. Создает раздел, но ни один из элементов.

Класс одного элемента

public class MyElement : ConfigurationElement
    {
        [ConfigurationProperty("uniqueIdentifier", IsRequired = true)]
        public string UniqueIdentifier
        {
            get
            {
                return base["uniqueIdentifier"].ToString();
            }
            set
            {
                base["uniqueIdentifier"] = value;
            }
        }

        [ConfigurationProperty("isOriginal", IsRequired = false, DefaultValue = false)]
        public bool IsOriginal
        {
            get
            {
                var value = false;
                if (bool.TryParse(base["isOriginal"].ToString(), out value))
                {
                    value = false;
                }

                return value;
            }
            set
            {
                base["isOriginal"] = value;
            }
        }

        internal string Key
        {
            get
            {
                return UniqueIdentifier;
            }
        }
    }

Класс коллекции

  [ConfigurationCollection(typeof(MyElement), AddItemName = "myElements", CollectionType = ConfigurationElementCollectionType.BasicMap)]
  public class MyElementCollection : ConfigurationElementCollection, IEnumerable<MyElement>
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((MyElement)element).Key;
    }

    public void Add(MyElement element)
    {
        BaseAdd(element);
    }

    public void Clear()
    {
        BaseClear();
    }

    public int IndexOf(MyElement element)
    {
        return BaseIndexOf(element);
    }

    public void Remove(MyElement element)
    {
        if (BaseIndexOf(element) >= 0)
        {
            BaseRemove(element.Key);
        }
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    IEnumerator<MyElement> IEnumerable<MyElement>.GetEnumerator()
    {
        int count = base.Count;
        for (int i = 0; i < count; i++)
        {
            yield return base.BaseGet(i) as MyElement;
        }
    }

    public MyElement this[int index]
    {
        get { return (MyElement)BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }
}

Класс пользовательских секций

  public class MyElementSection : ConfigurationSection
  {
    private static readonly ConfigurationProperty _elementCollection = new ConfigurationProperty(
            null,
            typeof(MyElementCollection),
            null,
            ConfigurationPropertyOptions.IsDefaultCollection
    );

    private static ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();

    static MyElementSection()
    {
        _properties.Add(_elementCollection);
    }

    [ConfigurationProperty("myElements")]
    public MyElementCollection MyElements
    {
        get
        {
            var b = base[_elementCollection];
            var collection = base[_elementCollection] as MyElementCollection;
            return collection;
        }
    }
}

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="myElements"
             type="TestConfigurationFiles.MyElementSection, TestConfigurationFiles"/>
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

Консоль Main

static void Main(string[] args)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            MyElementSection myElementsSection = configuration.GetSection("myElements") as MyElementSection;
            if (configuration.Sections["myElements"] == null)
            {
                configuration.Sections.Add("myElements", myElementsSection);
            }
            MyElementCollection myElements = myElementsSection.MyElements;

            myElements.Add(new MyElement { UniqueIdentifier = "One", IsOriginal = true});
            myElements.Add(new MyElement { UniqueIdentifier = "Two", IsOriginal = false });
            myElements.Add(new MyElement { UniqueIdentifier = "Three" });

            configuration.Save();
            ConfigurationManager.RefreshSection("myElements");

        }

После запуска программы класс exe.config содержит новый пустой раздел <myElements />.

<configuration>
  <configSections>
    <section name="myElements"
             type="TestConfigurationFiles.MyElementSection, TestConfigurationFiles"/>
  </configSections>
    <myElements />
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>
...