如何将格式化数据写入文件,然后读取?VB.NET(2012版)

如何将格式化数据写入文件,然后读取?VB.NET(2012版),vb.net,read-write,Vb.net,Read Write,我正在练习VB.NET,在读写.dat文件时遇到问题。我制作了一个临时存储数据的结构(如下) 然后我把所有东西都调暗 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}" 我有一个创建新帐户的按钮,这就是问题所在

我正在练习VB.NET,在读写.dat文件时遇到问题。我制作了一个临时存储数据的结构(如下)

然后我把所有东西都调暗

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)
我面临的主要问题是我做错了什么,我如何才能纠正它

多谢各位,
Jordan

首先,您需要导入以下名称空间:

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 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
用法

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
将名为
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
公共类表单1
公共分新()
Me.InitializeComponent()的缩写
端接头
私有子按钮1\u单击(发送者作为System.Object,e作为System.EventArgs)处理按钮1。单击

Dim path As String=“C:\test.dat”'您考虑过使用吗?我忘了说我也在学习过程中。你能不能给我一小段代码,这样我就可以理解发生了什么。MSDN是有帮助的,但并没有真正解释到我能理解的程度:)@Bjørn RogerKringsjå的例子很好。我同意这是一种更好的方法,因为您在.NET中。另外,我使用“FilePut”和“FileGet”处理您的代码-我很好奇,因为这些对我来说都是新的。我没有让他们使用那个结构。如果您确实喜欢这些类型的文件交互,您当然可以使用其他平面文件写入命令来保存数据。但是XML序列化解决了很多常见的问题(比如什么分隔符永远是安全的,强类型)。这本书有一章是关于文件的,这是他们如何做到的。这是一本很棒的书example@MikeM谢谢我认为最好让框架去/序列化。但当然,这完全取决于文件的使用方式。每次我想在列表中添加内容时,是否都必须对新项目进行模糊处理?哦,另外,请您为我解释一下“好友共享”部分好吗?:)@是的,这是一个。关于
朋友共享的
阅读和。
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
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