Search code examples
c#application-settings

C# Change all Settings files values


I have some forms and have made a Settings File for each that contains

int X
int Y
bool FirstRun

i save these for the user so that the position of the window is in the same spot every time they start the program. And i was thinking i would add a button to reset them to the standard value.

I found a way to save them to a list with

list<Type> settingsList = new list<Type>();

then

settingsList.Add(typeof(SettingsFileName));

But is there a way to make a foreach loop to change them all or do i need to do it manualy for them all?

--EDIT--

Left side the minimum a settings file will contain right side all settings files as of now Settings File Example

I save files with

AdminKontoplanSettings.Default.X = this.Location.X;
AdminKontoplanSettings.Default.Y = this.Location.Y;
AdminKontoplanSettings.Default.Height = this.Height;

AdminKontoplanSettings.Default.Save();

Solution

  • If you wish to iterate through your settings file, you should consider create an interface and let your settings classes inherit from it.
    The Settings classes are partial classes and you have one part that is controlled by the designer and one for you (From the designer you have a button "View code" to get to this part of the partial class).

    So you interface can look like:

    internal interface IMySettings
    {
        int X { get; set; }
        int Y { get; set; }
        bool FirstRun { get; set; }
        void Save(); 
    }
    

    The Save is to allow the saving operation when iterating.

    Your setting file might look like:

    internal sealed partial class MySettings : IMySettings
    

    And then, load all settings to a List<IMySettings> field and iterate through them.
    The tricky part would be to load them into the list, either you do it with reflection or by hand:

    var mySettingList = new List<IMySettings> {AdminKontoplanSettings.Default, MySetting.Defalut, AnotherSettings.Default ....}
    

    Then, on you "reset" button onclick method:

    foreach (var setting in this.mySettingList)
    {
      setting.X = 0;
      setting.Y = 0;
      setting.FirstRun = true;
      setting.Save();
    }