如何在应用程序启动之间保留对象列表

时间:2011-12-21 14:21:42

标签: c# .net c#-4.0

我需要在每个用户的应用程序启动之间保留一个对象列表;我怎么能这样做?

对象很简单:4个字符串和一个int。

4 个答案:

答案 0 :(得分:4)

Serialize用户appdata目录的对象,或者在您想要保留它时使用IsolatedStorage并在启动时反序列化它。

答案 1 :(得分:3)

最简单的方法是将它们存储为用户范围的应用程序设置

enter image description here

然后你可以通过静态属性访问它们

MyApplication.Properties.Settings.Default.StringOne = "herpaderp";
MyApplication.Properties.Settings.Default.Save();

答案 2 :(得分:1)

描述

一种方法是使用BinaryFormatter将可序列化对象列表保存到二进制文件中。如果您想要一个可读/可编辑的文件,可以使用SoapFormatter

示例

这是一个可以保存可序列化对象列表的类。

[Serializable]
public class BinareObjectList<T> : List<T>
{
    public void LoadFromFile(string fileName)
    {
        if (!File.Exists(fileName))
            throw new FileNotFoundException("File not found", fileName);

        this.Clear();

        try
        {
            IFormatter formatter = new BinaryFormatter();
            // IFormatter formatter = new SoapFormatter();
            Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            List<T> list = (List<T>)formatter.Deserialize(stream);
            foreach (T o in list)
                this.Add(o);
            stream.Close();
        }
        catch { }
    }

    public void SaveToFile(string fileName)
    {
        if (File.Exists(fileName))
            File.Delete(fileName);

        IFormatter formatter = new BinaryFormatter();
        // IFormatter formatter = new SoapFormatter();
        Stream stream = new FileStream(fileName, FileMode.CreateNew);
        formatter.Serialize(stream, this);
        stream.Close();
    }
}

更多信息:

更新

您在评论中说,您尝试保存应用程序设置。请考虑使用应用程序设置。

MSDN: Using Settings in C#

答案 3 :(得分:0)

我会投票给Isolated Storage