How to Save a List<String> on Settings.Default

How to save a List string on Settings.Default?

I found out that I can't directly save a List<string> on the application settings, but I saw that I can save a StringCollection.

And here I found out that it's very simple to convert from a StringCollection to a List<string>

var list = stringCollection.Cast<string>().ToList();

How save a list string in visual studio c# properties setting

The settings system provides a value type called StringCollection; make a setting of that type and scope user

Upon form load, add the contents of the collection to your list, perhaps with yourList.AddRange(Properties.Settings.Default.YourStringCollectionSetting)

Upon form closing (or whenever you save your settings) clear the settings string collection (Properties.Settings.Default.YourStringCollectionSetting.Clear())

and addrange your current list to it (Properties.Settings.Default.YourStringCollectionSetting.AddRange(yourList.ToArray()))

Why is this generic list not being saved in application settings?

TFS_Extraction.IterationFilter has to be serializable. The class is required to have a public default constructor.

Saving a list to My.Settings

A System.Collections.Specialized.StringCollection is the most common one used, although you cannot assign a List(Of String) to it directly as they are different types.

Instead you have to iterate your List(Of String) and add every item to the My.Settings list:

'Remove the old items.
My.Settings.Clear()

'Add the new ones.
For Each Item As String In Times
My.Settings.Times.Add(Item)
Next

Likewise, when reading it back into the List(Of String):

For Each Item As String In My.Settings.Times
Times.Add(Item)
Next

Save Properties.Settings.Default items to list, change the values and then save it to the file

You could access the settings by name, like so.

Settings.Default["Item1"];

Since you have the naming convention Item + Incrementing Number in your for loop you could do this,

for (int i = 0; i < list.Count; i++)
{
Settings.Default["Item" + i.ToString()] = listBox1.GetSelected(i);
}
Properties.Settings.Default.Save();

Properties.Settings does not save list view items

So you have items in listView1.Items and you want to save them to the WinForms Settings system.

Do it like so:

var settings = Properties.Settings.Default;
if( settings.ListViewItems is null ) settings.ListViewItems = new StringCollection();
foreach( ListViewItem lvi in listView1.Items )
{
settings.ListViewItems.Add( lvi.Text );
}
settings.Save();

Annoyingly, the StringCollection type has a method named AddRange but it only accepts String[] and not IEnumerable<String> - and .NET doesn't come with a stock AddRange method for the non-generic IList. So I recommend you avoid using the Settings system because it's weakly-typed and doesn't play-nice with the modern C# ecosystem, like support for Linq.



Related Topics



Leave a reply



Submit