2016-04-11 7 views
0

のリストを私のvb.netアプリで読み返して、オブジェクトをファイルにシリアライズします。私はこれを何度も何度もやります。 私のアプリを閉じる 私のアプリを起動して、私が書いたオブジェクトのリストを読み込もうとしましたが、動作しません。オブジェクトをファイルにシリアライズし、

これは私のモデルである:

<Serializable()> 
Public Class test 
    Public FontColor As Color = Color.Black 
    Public Contrast As Int32 = 0 
    Public Text As String = "" 
End Class 

これは私が私のファイルに書き込む方法です:

Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter 
Dim stream As New FileStream(Application.StartupPath + "\testme.txt", FileMode.Append, FileAccess.Write, FileShare.None) 
Dim TextValues As New test 
TextValues.Contrast = 10 
TextValues.FontColor = Color.AliceBlue 
TextValues.Text = "hello andy" 

formatter.Serialize(stream, TextValues) 
stream.Close() 

NB、はい、私は 'を使用' キーワードを使用する必要があります知っている:)

これはどのように私がそれを読み返すかです:

Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter 
Dim stream As New FileStream(Application.StartupPath + "\testme.txt", FileMode.Open, FileAccess.Read, FileShare.Read) 

REM THIS WORKS OK BUT FOR ONLY 1 OBJECT ****************************** 
Dim TextValues = CType(formatter.Deserialize(stream), test) 
REM ********************************************************************* 

REM ***THIS JUST ERRORS ************************************************* 
Dim TextValues2 = CType(formatter.Deserialize(stream), List(Of test)) 
REM ********************************************************************* 

stream.Close() 
+0

単一のオブジェクトをシリアライズするだけでリストをシリアライズするには、最初にリストを作成する必要があります。 –

+2

シリアル化されたファイルに追加しようとしないでください。 BinaryFormatterはそれぞれの新しい追加の前に型情報を追加します。そして、#3を読み込むにはまだ1と2を読み込まなければなりません。ランダムアクセスではありません。コレクションを作成して一度にすべて書き出します。それらを同じ方法で読んでください。 – Plutonix

+0

@VisualVincentはい、私は自分自身に来た結論:) –

答えて

0

List(Of TextValue)を作成し、複数のTextValueオブジェクトを作成して読み込みたい場合は、シリアル化/逆シリアル化することができます。

+0

@VisualVincent編集​​のおかげで、私はC#のほとんどの時間だと思う。 – Kateract

+0

私とVB.NETは同じです。 :) –

+0

あなたの提案に感謝します。しかし、一度に1つのファイルに追加する必要があります:( –

関連する問題