Reputation: 2748
I have a list as defined below that is populated from a GridView
. Everything is OK.
What is the best method of saving / loading this list to/from a file (XML or otherwise is OK)?
Note: In the future, I will be encrypting the file.
C# Code
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; }
}
}
Upvotes: 0
Views: 172
Reputation: 2748
Solution C# Code
#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;
}
Upvotes: 1
Reputation: 2666
ProtoBuf Net is a binary serializer but it is very flexible and fast
Upvotes: 2
Reputation: 17655
for structured data, either XML or a very lightweight SQL RDBMS like SQLite or SQL Server Compact Edition will work well
I recommend XML
reader/writer class for files because it is easily serialized
Serialization is an easy way to convert an object to a binary representation that can then be written to disk or sent over a wire.
Upvotes: 1