加载并保存列表

时间:2012-12-01 14:40:14

标签: c# xml list

我有一个由GridView填充的下面定义的列表。一切都很好。

将此列表保存/加载到文件中的最佳方法是什么(XML或其他方式可以)?

注意:将来我会加密文件。

C#代码

List<Item> lstNewItems = new List<Item>(); // Control Items  
lstNewItems.Clear();

foreach (GridViewRow PendingItemUnderControl in GridViewPendingList.Rows)
{
    Item NewItem = new Item();
    NewItem.Paramater = PendingItemUnderControl.Cells[0].Text.ToLower();
    NewItem.Type = (String)Session["BrowseType"];
    lstNewItems.Add(NewItem);
}

public class Item
{
    public Item(string Paramater, string Type)
    {         
        _Paramater = Paramater;
        _Type = Type;
    }
    private string _Paramater;
    [DataMember]
    public string Paramater
    {
        get { return _Paramater; }
        set { _Paramater = value; }
    }
    private string _Type;
    [DataMember]
    public string Type
    {
        get { return _Type; }
        set { _Type = value; }
    }
}

3 个答案:

答案 0 :(得分:2)

ProtoBuf Net是二进制序列化程序,但它非常灵活和快速

答案 1 :(得分:1)

对于结构化数据,XML或非常轻量级的SQL RDBMS(如SQLite或SQL Server Compact Edition)都可以正常运行

我建议XML读取器/编写器类用于文件,因为它很容易序列化 序列化是一种将对象转换为二进制表示的简单方法,然后可以将其写入磁盘或通过网络发送。

答案 2 :(得分:1)

解决方案C#代码

#region Save the object

            // Create a new XmlSerializer instance with the type of the test class
            XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Item>));

            // Create a new file stream to write the serialized object to a file
            TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
            SerializerObj.Serialize(WriteFileStream, lstNewItems);

            // Cleanup
            WriteFileStream.Close();

            #endregion

            // Load items to control
            #region Load the object

            // Create a new file stream for reading the XML file
            FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

            // Load the object saved above by using the Deserialize function
            List<Item> LoadedObj = (List<Item>)SerializerObj.Deserialize(ReadFileStream);

            // Cleanup
            ReadFileStream.Close();

            #endregion

            // Load up all the settings

            for (int i = 0; i < LoadedObj.Count; i++) // Loop through List with for
            {
                String ThisisAnItemToControl = LoadedObj[i].Paramater;
                String ThisIsItsType = LoadedObj[i].Type;
            }