2014-01-12 45 views
2

我正在練習VB.NET,並且在閱讀和寫入.dat文件時遇到了問題。我已經建立了一個臨時存儲數據的結構(見下文)。如何將格式化數據寫入文件然後讀取它? VB.NET(2012年版)

Structure CustomerType 
    Dim AccountNum As String 
    Dim Surname As String 
    Dim Forename As String 
    Dim Balance As Decimal 
End Structure 

然後我昏暗的一切。

Dim Customers(9) As CustomerType 
Dim Filename As String = "Accounts.dat" 
Dim NumberOfRecords As Short = 0 
Dim myFormat As String = "{0,-15}|{1,-15}|{2,-10}|{3,-10}" 

我有一個按鈕,創建一個新的帳戶,這是我得到的問題。

FileOpen(1, Filename, OpenMode.Random, , ,) 
    For i = 1 To Customers.Length() - 1 
     With Customers(i) 
      .Forename = InputBox("First name", "Forename") 
      Do Until .Forename <> "" And TypeOf .Forename Is String 
       .Forename = InputBox("First name", "Forename") 
      Loop 
      .Surname = InputBox("Surname", "Surname") 
      Do Until .Surname <> "" And TypeOf .Surname Is String 
       .Surname = InputBox("Surname", "Surname") 
      Loop 
      .AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number") 
      Do Until .AccountNum.Length = 8 And TypeOf .AccountNum Is String 
       .AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number") 
      Loop 
      .Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance") 
      Do Until .Balance > -1 
       .Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance") 
      Loop 
      FilePut(1, Customers, NumberOfRecords + 1) 
      NumberOfRecords += 1 
      lblNumberOfRecords.Text = NumberOfRecords 
     End With 
    Next 
    FileClose(1) 

我有另一個按鈕,顯示列表框中的數據。我只能得到一個項目才能顯示錯誤長度錯誤。

Dim Index As Integer 
    ListBox1.Items.Clear() 
    ListBox1.Items.Add(String.Format(myFormat, "Forename", "Surname", "Acc. Num.", "Balance")) 
    ListBox1.Items.Add("_____________________________________________________") 
    FileOpen(1, Filename, OpenMode.Random, , ,) 
    For Index = 1 To NumberOfRecords 
     FileGet(1, Customers) 
     ListBox1.Items.Add(String.Format(myFormat, Customers(Index).Forename, Customers(Index).Surname, Customers(Index).AccountNum, Format(Customers(Index).Balance, "currency"))) 
    Next Index 
    FileClose(1) 

我的主要問題是我做錯了什麼,我該如何解決?

許多在此先感謝, 喬丹

+0

您是否考慮過使用[serialization](http://msdn.microsoft.com/zh-cn/library/ms973893.aspx)? –

+0

我忘了說我也在學習過程中。你能否給我一小段代碼,以便我能理解正在發生的事情。 MSDN是有幫助的,但並沒有真正解釋它到我能理解的地步:) – Rinslep

+0

@Bjørn-RogerKringsjå的例子很棒。我同意這是一個更好的方法,因爲你在.NET中。 –

回答

3

首先,您需要導入這些命名空間:

Imports System.Runtime.Serialization 
Imports System.Runtime.Serialization.Formatters.Binary 
Imports System.IO 

型號

更改customertype模型如下:

<Serializable()> _ 
Public Class CustomerType 
    Implements ISerializable 

    Public Sub New() 
    End Sub 

    Protected Sub New(info As SerializationInfo, context As StreamingContext) 
     Me.AccountNum = info.GetString("AccountNum") 
     Me.Surname = info.GetString("Surname") 
     Me.Forename = info.GetString("Forename") 
     Me.Balance = info.GetDecimal("Balance") 
    End Sub 

    Public AccountNum As String 
    Public Surname As String 
    Public Forename As String 
    Public Balance As Decimal 

    Public Sub GetObjectData(info As System.Runtime.Serialization.SerializationInfo, context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData 
     info.AddValue("AccountNum", Me.AccountNum) 
     info.AddValue("Surname", Me.Surname) 
     info.AddValue("Forename", Me.Forename) 
     info.AddValue("Balance", Me.Balance) 
    End Sub 

End Class 

你的模型現在支持序列化。下一步是創建函數來讀取/寫入文件的模型集合。

Friend Shared Sub Write(filePathAndName As String, list As List(Of CustomerType)) 
    Dim formatter As IFormatter = New BinaryFormatter() 
    Using stream As New FileStream(filePathAndName, FileMode.Create, FileAccess.Write, FileShare.None) 
     formatter.Serialize(stream, list) 
    End Using 
End Sub 

Friend Shared Function Read(filePathAndName As String) As List(Of CustomerType) 
    Dim formatter As IFormatter = New BinaryFormatter() 
    Dim list As List(Of CustomerType) = Nothing 
    Using stream As New FileStream(filePathAndName, FileMode.Open, FileAccess.Read, FileShare.None) 
     list = DirectCast(formatter.Deserialize(stream), List(Of CustomerType)) 
    End Using 
    Return list 
End Function 

使用

刪除按鈕命名爲Button1到一個名爲Form1形式,並添加以下代碼:

Public Class Form1 

    Public Sub New() 
     Me.InitializeComponent() 
    End Sub 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 

     Dim path As String = "C:\test.dat" '<- Change to desired path 
     Dim list As New List(Of CustomerType) 

     'Create test item1 and add to list. 
     Dim item1 As New CustomerType() 
     With item1 
      .AccountNum = "1" 
      .Balance = 1000D 
      .Forename = "Forename 1" 
      .Surname = "Surname 1" 
     End With 
     list.Add(item1) 

     'Create test item2 and add to list. 
     Dim item2 As New CustomerType() 
     With item2 
      .AccountNum = "2" 
      .Balance = 2000D 
      .Forename = "Forename 2" 
      .Surname = "Surname 2" 
     End With 
     list.Add(item2) 

     'Write to file: 
     Write(path, list) 

     'Read from file into new list: 
     Dim list2 As List(Of CustomerType) = Read(path) 

     MsgBox(String.Format("Count={0}", list2.Count)) 

    End Sub 

    Friend Shared Sub Write(filePathAndName As String, list As List(Of CustomerType)) 
     Dim formatter As IFormatter = New BinaryFormatter() 
     Using stream As New FileStream(filePathAndName, FileMode.Create, FileAccess.Write, FileShare.None) 
      formatter.Serialize(stream, list) 
     End Using 
    End Sub 

    Friend Shared Function Read(filePathAndName As String) As List(Of CustomerType) 
     Dim formatter As IFormatter = New BinaryFormatter() 
     Dim list As List(Of CustomerType) = Nothing 
     Using stream As New FileStream(filePathAndName, FileMode.Open, FileAccess.Read, FileShare.None) 
      list = DirectCast(formatter.Deserialize(stream), List(Of CustomerType)) 
     End Using 
     Return list 
    End Function 

End Class 
+0

這是一個很好的例子 –

+0

@MikeM謝謝!我認爲最好讓框架去de /序列化。但是,這當然取決於文件的使用方式。 –

+0

每次我想添加一些東西到列表中時,是否必須調暗新項目? – Rinslep

相關問題