简体   繁体   中英

How to save a List<INetFwRule2> on Settings.Default?

I have a ruleList in my form, I want to save every item in it and load the values when i start the application again.

So I created a new settings tab in Properties -> Settings

Edited Settings.settings file like this :

<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="fireWall.Properties" GeneratedClassName="Settings">
  <Profiles />
  <Settings>
    <Setting Name="Location" Type="System.Drawing.Point" Scope="User">
      <Value Profile="(Default)">50, 50</Value>
    </Setting>
    <Setting Name="FormSize" Type="System.Drawing.Size" Scope="User">
      <Value Profile="(Default)">800, 600</Value>
    </Setting>
    <Setting Name="FirewallList" Type="System.Collections.Generic.List&lt;NetFwTypeLib.INetFwRule2&gt;" Scope="User">
      <Value Profile="(Default)" />
    </Setting>
    <Setting Name="myTestDataList" Type="System.Collections.Generic.List&lt;System.String&gt;" Scope="User">
      <Value Profile="(Default)" />
    </Setting>
  </Settings>
</SettingsFile>

and finally I saved my list on FormClosing : Properties.Settings.Default["FirewallList"] = RuleList;

However when I try to load my rules from user settings

RuleList = Properties.Settings.Default["FirewallList"] as List<INetFwRule2>;

I get a null exception error.

My Closing Form :

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

         // saving windows size and location

            Properties.Settings.Default.FormSize = this.Size;
            Properties.Settings.Default.Location = this.Location;

         // saving RuleList

         Properties.Settings.Default["FirewallList"] = RuleList;

         // saving list of random Strings

            Properties.Settings.Default.myTestDataList = new List<String>();

            Properties.Settings.Default.myTestDataList.Add("stack");
            Properties.Settings.Default.myTestDataList.Add("overflow");
            Properties.Settings.Default.myTestDataList.Add(".com");

         // saving all settings

            Properties.Settings.Default.Save();
        }

PS : Am I doing right saving a list to user settings? Would a custom .txt file for example be suitable for my situation?

Using settings at runtime. Take a look at MSDN here :

Access the user setting and assign it a new value, as shown in the following example:

Properties.Settings.Default.myColor = Color.AliceBlue;

If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:

Properties.Settings.Default.Save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM