【问题标题】:Store array[,] in user settings在用户设置中存储 array[,]
【发布时间】:2012-07-29 03:11:22
【问题描述】:

如何在程序的设置中存储一个双精度数组,然后再检索它?


代码

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;

如您所见,我是否使用用户的 id 将信息存储在一起。我是这样存储的:

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

我做得对吗?现在数组还在用户设置里吗?

我怎样才能摆脱它(具有正确用户 ID 的设置)?

我知道这听起来很疯狂,但我认为这是最好的方法。但如果你们知道更好的方法,请告诉我。我

编辑 1:

我有这段代码:

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());

运行代码后,XML 文件如下所示:

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

现在我不明白为什么没有保存数组。因为我有这条线

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

我认为这会从数组中获取用户设置,但不知何故他们没有。

【问题讨论】:

  • 已经完成了,但我确实希望我可以像他们已经使用的那样使用多维数组,所以不需要处理拆分和解析......

标签: c# arrays multidimensional-array settings


【解决方案1】:

使用System.Collections.Specialized.StringCollection 设置并为每个字符串添加一个 XML 字符串(包含您的附加属性,如 'user_name' 或 'user_email'):

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

并在需要属性时解析 XML。

【讨论】:

    【解决方案2】:

    好吧,通常我只使用http://www.sharpserializer.com/en/index.html

    它非常容易使用,速度很快,并且可以或多或少地序列化任何东西,包括字典等。 好消息是,您可以序列化为多种目标格式,例如二进制。

    编辑:使用 SharpSerializer 进行序列化的示例。 没有编译代码,但应该没问题。 缺点:要存储的属性必须是公开的...

    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.
           }
    }
    

    【讨论】:

    • 看起来不错,我去看看;-)
    • 好吧,我已经把它包括在内,搜索了源代码之类的东西......但我不知道如何添加我的数组 (string[,] user_credits = new string [user_credits_array, 10];) 到 xml 文件,以及我以后如何从文件中接收该信息....你能帮我指出我必须做什么吗???
    • 好的,我已经将它添加到我的项目(新类文件)中,我现在将如何使用它?因为只看到XML文件的路径发生了一些事情(如果我是对的?!?)那么我该如何保存我的数组呢?或者您可以在您提供的代码中添加一些 cmets,以便我了解发生了什么?感谢您已经完成的所有工作。我希望我能很快理解这是如何工作的:P
    • 您可以在代码中添加一些注释吗?所以我能比现在更好地理解它吗?
    • 希望,现在你可以看到这是怎么回事。还有更多关于如何使用 SharpSerializer 的信息 [sharpserializer.com/en/tutorial/index.html#a23]here.
    【解决方案3】:

    啊,我看到了问题。 正如您在 XML 文件中看到的,MySettings 实例(settingsTest)中的数组为空。 那是因为您在 settingsTest 对象之外填充数组,并且从不触摸或初始化 settingsTest.user_credits...

    尝试以下方法:

    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());
    

    【讨论】:

    • 好的,这很有效 :-D 非常感谢您对我的帮助。我非常感谢你:D 谢谢
    【解决方案4】:

    啊,我们在 2012 年还很年轻……而是使用 JSON 序列化程序来保存您的项目列表(或数组)。我的示例使用了一个名为MRU 的类而不是双精度类,但思路是一样的:

    进入设置

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

    超出设置

    var mruText = Properties.Settings.Default.MRUS;
    return string.IsNullOrWhiteSpace(mruText) ? new List<MRU>()
        : JsonSerializer.Deserialize<List<MRU>>(mruText);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      相关资源
      最近更新 更多