1

How can one store a double array in the settings of the program, and retrieve it later?


Code

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

So as you can see, am i using the id of the user to store the info together. And I'm storing it this way:

Properties.Settings.Default.user_credits = user_credits;
Properties.Settings.Default.Save();

Am I doing it right? is now the array still in the user settings?

And how can I get it out of it (the settings with the right user id)?

I know it might sound crazy, but i think this is the best way. But if you guys know an better way, tell me. I

Edit 1:

I've got this piece of code:

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

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

And after running the code, this is how the XML file looks like:

<Complex name="Root" type="WeProgram_Mail.MySettings, WeProgram_Mail, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
  <Properties>
    <Null name="user_credits" />
  </Properties>

Now I don't understand why the array isn't saved. Because I've got this line

public string[,] user_credits { get; set; }

And I thought that would pick up the usersettings from the array, but somehow they don't.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Mathlight
  • 6,436
  • 17
  • 62
  • 107
  • Have a look at this question http://stackoverflow.com/questions/1766610/how-to-store-int-array-in-application-settings – zeencat Jul 31 '12 at 11:14
  • already done, but i did hope that i could just use multidimensiol array like they already are, so no processing of splitting and parsing.... – Mathlight Jul 31 '12 at 12:01

4 Answers4

3

Use System.Collections.Specialized.StringCollection for setting and add a XML String (contain your additional properties like 'user_name' or 'user_email') to each string:

var collection = new StringCollection {"<user_name>aaaa<user_name><user_email>asdfasd@asdfasd</user_email>"};
Properties.Settings.Default.MySetting = collection;
Properties.Settings.Default.Save();

and parse XML when you need properties.

Ria
  • 10,237
  • 3
  • 33
  • 60
2

Well, usually I just use http://www.sharpserializer.com/en/index.html

It is childishly easy to use, fast, and can serialize more or less anything, including Dictionary, etc. Nice thing is, that you can serialize to multiple target formats like binary.

EDIT: Example for Serialization with SharpSerializer. Have not compiled the code, but should be fine. Drawback: A property to be stored has to be public...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Polenter.Serialization;

namespace Test
{
    public class MySettings
    {
        // this is a property we want to serialize along with the settings class.
        // the serializer will automatically recognize it and serialize/deserialize it.
        public string[,] user_credits { get; set; }

        //
        public static MySettings Load(string path)
        {
            if (!System.IO.File.Exists(path)) throw new System.ArgumentException("File \"" + path + "\" does not exist.");
            try
            {
                MySettings result = null;
                // the serialization settings are just a needed standard object as long as you don't want to do something special.
                SharpSerializerXmlSettings settings = new SharpSerializerXmlSettings();
                // create the serializer.
                SharpSerializer serializer = new SharpSerializer(settings);
                // deserialize from File and receive an object containing our deserialized settings, that means: a MySettings Object with every public property in the state that they were saved in.
                result = (MySettings)serializer.Deserialize(path);
                // return deserialized settings.
                return result;
            }
            catch (Exception err)
            {
                throw new InvalidOperationException(string.Format("Error in MySettings.LoadConfiguration():\r\nMessage:\r\n{0}\r\nStackTrace:\r\n{1}", err.Message, err.StackTrace), err);
            }
        }

        public void Save(string targetPath)
        {
            try
            {
                // if the file isn't there, we can't deserialize.
                if (String.IsNullOrEmpty(targetPath))
                    targetPath = GetDefaultPath();

                SharpSerializerXmlSettings settings = new SharpSerializerXmlSettings();
                SharpSerializer serializer = new SharpSerializer(settings);
                // create a serialized representation of our MySettings instance, and write it to a file.
                serializer.Serialize(this, targetPath);
            }
            catch (Exception err)
            {
                throw new InvalidOperationException(string.Format("Error in MySettings.Save(string targetPath):\r\nMessage:\r\n{0}\r\nStackTrace:\r\n{1}", err.Message, err.StackTrace), err);
            }
        }

        public static string GetDefaultPath()
        {
            string result = string.Empty;
            try
            {
                // Use Reflection to get the path of the Assembly MySettings is defined in.
                string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                // remove the file:// prefix for local files, or file:/// for network/unc paths
                if (path.StartsWith("file:///"))
                    path = path.Remove(0, "file:///".Length);
                else if (path.StartsWith("file://"))
                    path = path.Remove(0, "file://".Length);
                // get the path without filename of the assembly
                path = System.IO.Path.GetDirectoryName(path);
                // append default filename "MySettings.xml" as default filename for the settings.
                return System.IO.Path.Combine(path, "MySettings.xml");
            }
            catch (Exception err)
            {
                 throw new InvalidOperationException(string.Format("Error in MySettings.GetDefaultPath():\r\nMessage:\r\n{0}\r\nStackTrace:\r\n{1}", err.Message, err.StackTrace), err);
            }
        }
    }

    public class Test
    {
       public void Test()
       {
          // create settings for testing
          MySettings settingsTest = new MySettings();
          // save settings to file. You could also pass a path created from a SaveFileDialog, or sth. similar.
          settingsTest.Save(MySettings.GetDefaultPath());
          // Load settings. You could also pass a path created from an OpenFileDialog.
          MySettings anotherTest = MySettings.Load(MySettings.GetDefaultPath());
          // do stuff with the settings.
       }
}
mw_21
  • 150
  • 5
  • Looks nice, i will have a look at it ;-) – Mathlight Jul 31 '12 at 12:00
  • alright, i've got it included, searched the source code an all that kind of stuff... but i don't know how to add my array (string[,] user_credits = new string[user_credits_array, 10];) to the xml file, and how i can later recief that info from the file.... Can you give me an hand and point out what i have to do??? – Mathlight Jul 31 '12 at 12:31
  • alright, i've added this to my project (new class file), and how am i gonna use this now? because is see only some stuff happening with the path of the XML file (if im right?!?) So how do i save my array with this? Or can you add some comments to the code you gave, so i can understand what's happening? Thanks for all the work already given. I hope i will understand verry soon how this work :P – Mathlight Jul 31 '12 at 13:35
  • Can you add some comment to the code? so i can understand it much better then i do now? – Mathlight Jul 31 '12 at 14:00
  • Hope, now you can see where this is going. There is also more info on how to use SharpSerializer [http://www.sharpserializer.com/en/tutorial/index.html#a23]here. – mw_21 Jul 31 '12 at 14:20
  • Alright, i've got no errors, and the XML file is created, but somehow the array isn't filled in the XML file. I've updated my question (edit 1), to explain it a little bit. Hope you can help me, because i'm feeling myself verry dump.... – Mathlight Jul 31 '12 at 15:00
1

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());
mw_21
  • 150
  • 5
  • Alright, That worked :-D Thank you so much for your work to help me. i cannot thank you enough :D Thanks – Mathlight Jul 31 '12 at 15:35
1

Ahh we were so young back in 2012....instead use the JSON serializer to save your list (or array) of items. My example uses a class named MRU instead of doubles, but the thought is the same:

Into Settings

 // Extract from ObservableCollection<MRU>.
 List<MRU> asList = MRUS.ToList<MRU>();
 Properties.Settings.Default.MRUS = JsonSerializer.Serialize(asList);
 Properties.Settings.Default.Save();

Out of Settings

var mruText = Properties.Settings.Default.MRUS;
return string.IsNullOrWhiteSpace(mruText) ? new List<MRU>()
    : JsonSerializer.Deserialize<List<MRU>>(mruText);
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122