在我的「DiaryManager」類中,我得到了兩個具有兩種不同類型(T)的List,我想將它保存到文件中,然後我想加載它。 我已經將它與我的列表中的一個一起工作,因爲我將向您展示。將兩個列表保存到文件中,然後加載c#
我在我的工作代碼中保存和加載的列表被命名爲「m_diary」。保存方法是這樣的一個:
/// <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);
}
}
我的加載方法是這樣的一個:
/// <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);
}
}
}
的 「DATA_FILENAME」 是本恆:
private const string DATA_FILENAME = "TrainingDiary.dat";
此代碼的工作完美,從我窗體類。 但是現在Iv又添加了一個不同類型的列表。
如何保存並加載第二個列表? :)
問候 Cyrix的
有幾個選項 - 把你的兩個列表放到類中,然後序列化這個類;將每個列表保存爲不同的文件;手動執行序列化 - 使用某種類型的分隔符 – JleruOHeP
與當前問題無關,但請查看[using語句](http://msdn.microsoft.com/zh-cn/library/yh598w02 (VS.80).aspx)關於你的'FileStream'對象。 – Default