2012-04-28 37 views
-1

嗨我想知道如何保留以前的記錄與我的流編寫器,如果我使用下面的代碼,它工作正常時創建學生記錄,但是當我創建第二個學生記錄時,以前的記錄不見了?我如何保存所有記錄?StreamWriter覆蓋以前的記錄?

public void AddStudent(Student student) 
    { 
     students.Add(student); 
     XmlSerializer s = new XmlSerializer(typeof(Student)); 
     TextWriter w = new StreamWriter("c:\\list.xml"); 
     s.Serialize(w, student); 
     w.Close(); 
    } 

編輯更新:

從部分答案下面我不斷收到此錯誤Type WcfServiceLibrary1.Student' in Assembly 'WcfServiceLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable

我裝飾了學生類具有[Serializable()]所以林不知道怎麼回事?

回答

1

使用this重寫StreamWriter的構造函數來附加新數據而不是覆蓋。

TextWriter w = new StreamWriter("c:\\list.xml", true); 


更新: 我看,它僅適用於BinaryFormatter的,而不是與XmlSerializer的,因爲第二個寫使XML無效。除非您出於某種原因需要XML格式,否則使用二進制格式更容易。這應該工作:

static void WriteStudent(Student S) 
    { 
     BinaryFormatter f = new BinaryFormatter(); 
     using (Stream w = new FileStream("c:\\list.dat", FileMode.Append)) 
     { 
      f.Serialize(w, S); 
     } 
    } 

    static List<Student> ReadStudents() 
    { 
     BinaryFormatter f = new BinaryFormatter(); 

     using (Stream w = new FileStream("c:\\list.dat", FileMode.Open)) 
     { 
      List<Student> students = new List<Student>(); 
      while (w.Position < w.Length) 
      { 
       students.Add((Student)f.Deserialize(w)); 
      } 
      return students; 
     } 
    } 
+0

這不起作用。同樣的問題,但不是我的方式你的方式ontop不追加也失去了第二次運行xml文檔中的xml格式。 – 2012-04-28 23:41:15

+0

WriteStudent拋出一個異常:類型'WcfServiceLibrary1.Student'在組件'WcfServiceLibrary1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'未被標記爲可序列化。' – 2012-04-29 10:12:31

+0

@JungleBoogie:這意味着你必須修飾學生類與[Serializable](http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx)屬性。 – 2012-04-29 10:33:21

1

您正在做的是打開文件,放棄現有內容,將Student類型的單個student對象序列化爲XML,將XML寫入文件並關閉它。

你必須做的幾乎完全一樣,除了你必須序列化學生列表而不是一個單一的。爲此,嘗試這樣做:

s.Serialize(w, students); 

,而不是這樣的:

s.Serialize(w, student); 

而且不要忘了修改typeof(Student)到任何類,你正在使用,以保持一個列表將typeof(將是一種students對象)。

+0

嗨弗拉德使用的學生(這足夠有趣的是我的名單被命名,返回一個錯誤,生成XML文檔時出錯...是的,謝謝你的Visual Studio非常翔實! – 2012-04-28 23:39:16

+0

你是正確的,我放棄了現有的內容,但我也想序列化一個學生,因爲這是一個休息時間,每次只創建一個學生,所以我想要做的就是「追加」下一個創建的學生集合。 – 2012-04-28 23:54:09

+0

@ JungleBoogie:然後用Nuf的答案:)我的意思是,真的,你還能做什麼?解析整個文件,將學生添加到解析列表中,然後再次序列化它... – 2012-04-29 00:06:10

0

它不會按照您期望的方式工作。 StreamWriter將不會做任何魔法,以便在根元素中插入新的Student記錄。您需要從文件反序列化列表,添加新條目並將其序列化。或者,您可以將學生列表保留在內存中,向其添加新記錄,然後序列化整個組。

這些都不是存儲增量更新的特別好方法。您應該考慮使用SQL Server(或快速)代替。