How to Store Int[] Array in Application Settings

How to store int[] array in application Settings

There is also another solution - requires a bit of manual editing of the settings file, but afterwards works fine in VS environment and in the code. And requires no additional functions or wrappers.

The thing is, that VS allows to serialize int[] type by default in the settings file - it just doesn't allow you to select it by default.
So, create a setting with desired name (e.g. SomeTestSetting) and make it of any type (e.g. string by default).
Save the changes.

Now go to your project folder and open the "Properties\Settings.settings" file with text editor (Notepad, for example) Or you can open it in VS by right-clicking in Solution Explorer on " -> Properties -> Settings.settings", select "Open With..." and then choose either "XML Editor" or "Source Code (Text) Editor".
In the opened xml settings find your setting (it will look like this):

<Setting Name="SomeTestSetting" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>

Change the "Type" param from System.String to System.Int32[]. Now this section will look like this:

<Setting Name="SomeTestSetting" Type="System.Int32[]" Scope="User">
<Value Profile="(Default)" />
</Setting>

Now save changes and re-open project settings - voilà! - We have the setting SomeTestSetting with type System.Int32[] which can be accessed and edited through VS Settings Designer (values too), as well as in the code.

Store array[,] in user settings

Ah, I see the problem.
As you see in the XML file, the array in the MySettings instance(settingsTest) is null.
That is because you fill the array outside the settingsTest object and never touch or initialize settingsTest.user_credits...

Try the following:

MySettings settingsTest = new MySettings();
settingsTest.user_credits = new string[user_credits_array, 10];
settingsTest.user_credits[new_user_id, 0] = user_name;
settingsTest.user_credits[new_user_id, 1] = user_email;
settingsTest.user_credits[new_user_id, 2] = user_acc_name;
settingsTest.user_credits[new_user_id, 3] = user_acc_pass;
settingsTest.user_credits[new_user_id, 4] = sSelectedClient;
settingsTest.user_credits[new_user_id, 5] = server_inkomend;
settingsTest.user_credits[new_user_id, 6] = server_uitgaand;
settingsTest.user_credits[new_user_id, 7] = server_port + "";
settingsTest.user_credits[new_user_id, 8] = ssl_state;

settingsTest.Save(MySettings.GetDefaultPath());
MySettings anotherTest = MySettings.Load(MySettings.GetDefaultPath());

Store String Array with Values in Application Settings

Try to use StringCollection instead of string[]. It is natively supported by the settings designer.

The value is stored as XML, but you don't need to edit it manually. When you select StringCollection in the Type column, the editor in the Value column changes; there is a ... button, which opens a dialog to type the strings.

Sample Image

How do I store an array of a particular type into my settings file?

I found the source of the problem. Simply using a plain Array won't cut it. After thinking about it, the deserializer wouldn't know what type to deserialize the array items to. I failed to see that the array required strong typing. The designer lead me to foolishly believe it was a plain generic array:

    [global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public List<Link> Links
{
get {
return ((List<Link>)(this["Links"]));
}
set {
this["Links"] = value;
}
}

I had to make these changes in the Settings.Designer.cs and not from the designer.

Array of structures in Application Settings

You might consider having a custom string for the value portion, one which you can parse (similar to a connection string), and then require a key name that begins with a constant, like ServerString. Then you can have a method in your code that reads all the keys that begin with this constant and parse the value portion into a Tuple.

For example, consider the app.config values:

  <appSettings>
<add key="ServerString1" value="name=MyServerName;address=127.0.0.1;port=80" />
<add key="ServerString2" value="name=MyServerName;address=127.0.0.2;port=81" />
<add key="ServerString3" value="name=MyServerName;address=127.0.0.3;port=82" />
</appSettings>

And consider a method that knows how to parse a valid value string into a Tuple<string, string, int>:

private static Tuple<string, string, int> GetTupleFromServerSetting(string serverSetting)
{
if (serverSetting == null) throw new ArgumentNullException("serverSetting");
var settings = serverSetting.Split(';');

if (settings.Length != 3)
throw new ArgumentException("One or more server settings is missing.",
"serverSetting");

var name = string.Empty;
var address = string.Empty;
int port = 0;

foreach (var setting in settings)
{
var settingParts = setting.Split('=');

if (settingParts.Length != 2)
throw new ArgumentException(string.Format(
"Setting is missing a value: {0}", setting),
"serverSetting");

switch (settingParts[0].ToLower())
{
case "name":
name = settingParts[1];
break;
case "address":
address = settingParts[1];
break;
case "port":
port = int.Parse(settingParts[1]);
break;
}
}

return new Tuple<string, string, int>(name, address, port);
}

Then, when you're parsing your app.config, you could do something like this to get a list of all the server settings:

List<Tuple<string, string, int>> serverSettings =
ConfigurationManager.AppSettings.AllKeys.Where(key =>
key.StartsWith("ServerString", StringComparison.OrdinalIgnoreCase))
.Select(key => GetTupleFromServerSetting(ConfigurationManager.AppSettings[key]))
.ToList();

Store String Array In appSettings?

You could use the AppSettings with a System.Collections.Specialized.StringCollection.

var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myStringCollection)
{
// do something
}

Each value is separated by a new line.

Here's a screenshot (german IDE but it might be helpful anyway)

Sample Image

How to store a list of objects in application settings

You can use BinaryFormatter to serialize list of tuples as byte array and Base64 (as quite efficient way) to store byte array as string.

First of all change your class to something like that (hint: [SerializableAttribute]):

[Serializable()]
public class tuple
{
public tuple()
{
this.font = new Font("Microsoft Sans Serif", 8);
//....
}

Add property in settings named tuples and type of string.

tuples in Settings

Then you can use two methods to load and save generic list of tuples (List<tuple>):

void SaveTuples(List<tuple> tuples)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, tuples);
ms.Position = 0;
byte[] buffer = new byte[(int)ms.Length];
ms.Read(buffer, 0, buffer.Length);
Properties.Settings.Default.tuples = Convert.ToBase64String(buffer);
Properties.Settings.Default.Save();
}
}

List<tuple> LoadTuples()
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(Properties.Settings.Default.tuples)))
{
BinaryFormatter bf = new BinaryFormatter();
return (List<tuple>)bf.Deserialize(ms);
}
}

Example:

List<tuple> list = new List<tuple>();
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());

// save list
SaveTuples(list);

// load list
list = LoadTuples();

I leave null, empty string and exception checking up to you.

C# App.Config with array or list like data

The easiest way would be a comma separated list in your App.config file. Of course you can write your own configuration section, but what is the point of doing that if it is just an array of strings, keep it simple.

<configuration>
<appSettings>
<add key="ips" value="z,x,d,e" />
</appSettings>
</configuration>

public string[] ipArray = ConfigurationManager.AppSettings["ips"].Split(',');

How can I store an array of strings at runtime to a single application settings property?

Potential issues: what value does serverCounter.Value have? How is us.ServerName[] instantiated? ServerName returns a string array, but to me it looks like each serverName should be a string, and then put into an array (or list).

From the code snippet you show, my guess is that serverCounter has a certain value >1 and us.ServerName always is an array with 1 item (or it is never instantiated). This will give you an index out of range error.

Try using public string ServerName instead of public String[] ServerName and then each time you get a return value, put that value into an array--or if you don't know how many servers will be inputted, a List would be better.

List<string> serverNames = new List<string>();

// Get currentName from user--I don't understand how your code is supposed to work

serverNames.Add(currentName); // this is the name entered by the user

Then use a foreach loop:

        foreach (string name in serverNames)
{
//do something
}

If you know in advance how many servers there are, you can use a string array:

string[] serverNames = new string[serverCounter];

and still use a foreach loop to iterate over it.

How can I store an array in my.settings in vb.net

Set up your setting in Project Properties, Settings tab as follows.
Sample Image

Then save the setting as follows.

Private Sub SaveStringToSettings()
My.Settings.StringOfInts = TextBox1.Text 'User types in {1, 2, 3}
End Sub

To retrieve the setting and turn it into an array

Private Sub CreateArrayFromSettings()
Dim SettingValue = My.Settings.StringOfInts
Debug.Print(SettingValue) 'View this in the Immediate window
'Get rid of the braces
Dim TrimmedString = SettingValue.Trim({"{"c, "}"c})
'Split the string by the commas into an array
Dim Splits = TrimmedString.Split(","c)
'Get rid of the spaces
For i = 0 To Splits.Length - 1
Splits(i) = Splits(i).Trim
Next
TextBox1.Text = Splits(0) 'Displays 1
End Sub


Related Topics



Leave a reply



Submit