In my class “DiaryManager” I got two List with two different types (T) and I want to save it to file, then I want to load it.
I got it to work with one of my list’s as I am going to show you.
My list that I save and load in my working code is named “m_diary”. The save method is this one:
/// <summary>
/// Saves the object information
/// </summary>
public void Save()
{
// Gain code access to the file that we are going
// to write to
try
{
// Create a FileStream that will write data to file.
FileStream writerFileStream =
new FileStream(DATA_FILENAME, FileMode.Create, FileAccess.Write);
// Save our dictionary of friends to file
m_formatter.Serialize(writerFileStream, m_diary);
// Close the writerFileStream when we are done.
writerFileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And my load method is this one:
/// <summary>
/// Load the object to the program
/// </summary>
public void Load()
{
// Check if we had previously Save information of our friends
// previously
if (File.Exists(DATA_FILENAME))
{
try
{
// Create a FileStream will gain read access to the
// data file.
FileStream readerFileStream = new FileStream(DATA_FILENAME,
FileMode.Open, FileAccess.Read);
// Reconstruct information of our friends from file.
m_diary = (List<Diary>)
m_formatter.Deserialize(readerFileStream);
// Close the readerFileStream when we are done
readerFileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The “DATA_FILENAME” is this constant:
private const string DATA_FILENAME = "TrainingDiary.dat";
This code works perfect from my windows form class.
But now Iv added one more list with a different type.
How do I save and load that second list to?? 🙂
Best regards
Cyrix
You can do it using similar code for the second list, or you can write a generic method:
And a load method:
Usage of Load:
Also see using Statement to handle open/close streams;