VB.net读写二进制文件

本示例阐释二进制文件的基本输入和输出(使用 BinaryReader、BinaryWriter 和 FileStream 类。 在如何创建日志文件标题下面有一个类似的主题。读写二进制信息使您可以创建和使用通过其他输入和输出方法无法访问的文件。本示例还展示写入非字符串数据,并展示二进制 I/O 的功能。 
  
尽管计算机上的文件可以不同的类型和文件存储,但是,二进制格式是文件的较常用格式之一。此处对创建二进制文件的简短介绍使用基类 BinaryReader 和 BinaryWriter 从文件获取信息,并将信息放入文件。这些类中的每个类均封装一个信息流,因此,在进一步操作之前,需要创建一个可用于来回写信息的流。因为要创建文件,所以可使用 FileStream 来公开特定文件,在此情况下,如果该文件已存在,则可以修改该文件,或者如果该文件尚不存在,则可以创建该文件。在有 FileStream 之后,可以使用它来构造 BinaryReader 和 BinaryWriter,如下面的示例所示。 


//Make a new FileStream object, exposing our data file.
//If the file exists, open it, and if it doesn't, then Create it.
FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate);

//create the reader and writer, based on our file stream
BinaryWriter w = new BinaryWriter(fs);

BinaryReader r = new BinaryReader(fs);

或者写成以下的形式,

' Make a new FileStream object, exposing our data file.
' If the file exists, open it, and if it doesn't, then Create it.
Dim fs As FileStream = New FileStream("data.bin", FileMode.OpenOrCreate)

' create the reader and writer, based on our file stream
Dim w As BinaryWriter = New BinaryWriter(fs)
Dim r As BinaryReader = New BinaryReader(fs)

 若要使用 BinaryReader,可用若干不同的 Read 方法来解释从所选流读取的二进制信息。因为本示例处理二进制信息,所以您将使用 ReadString 方法,但是,BinaryReader 公开 ReadBoolean 或 ReadChar 等其他阅读器来解释其他数据类型。当从流读取信息时,使用 PeekChar 方法来确定是否已到达流结尾(本例中为文件结尾)。在到达流结尾之后,PeekChar 返回一个负值,如下面的示例所示。 


//make an appropriate receptacle for the information being read in...
//a StringBuilder is a good choice
StringBuilder output = new StringBuilder();

//set the file pointer to the beginning of our file...
r.BaseStream.Seek(0, SeekOrigin.Begin);

//continue to perform this loop while not at the end of our file...
while (r.PeekChar() > -1)
{
output.Append( r.ReadString() ); //use ReadString to read from the file
}
或者写成以下的形式,

' make an appropriate receptacle for the information being read in...
' a StringBuilder is a good choice
Dim output as StringBuilder = New StringBuilder()

' set the file pointer to the beginning of our file...
r.BaseStream.Seek(0, SeekOrigin.Begin)

' continue to perform this loop while not at the end of our file...
Do While r.PeekChar() > -1

output.Append( r.ReadString() )  ' use ReadString to read from the file
Loop

在读入信息之后,可以对信息进行所需的任何操作。但是,在某些时候,您可能想要将信息写回文件,因此需要 BinaryWriter。在本示例中,您将使用 Seek 方法将信息追加到文件结尾,因此,在开始写入之前,请确保指向文件的指针位于文件结尾。在使用 BinaryWriter 写入信息时有多个选项。因为 Write 方法有足够的重载用于您能够写入的所有信息类型,所以,可以使用 Write 方法向您的编写器封装的流写入任何标准形式的信息。本情况下,还可以使用 WriteString 方法向流中写入长度预先固定的字符串。本示例使用 Write 方法。注意 Write 方法确实接受字符串。 


//set the file pointer to the end of our file...
w.BaseStream.Seek(0, SeekOrigin.End);

w.Write("Putting a new set of entries into the binary file...\r\n");



for (int i = 0; i < 5; i++) //some arbitrary information to write to the file
{
w.Write( i.ToString() );
}


' set the file pointer to the end of our file...
w.BaseStream.Seek(0, SeekOrigin.End)

w.Write("Putting a new set of entries into the binary file..." & chr(13))

Dim i As Integer

For i = 0 To 5 Step 1       ' some arbitrary information to write to the file

w.Write( i.ToString() )
Next i

 
C#  VB    


在展示了读写二进制信息的基本知识以后,最好打开用 Microsoft Word 或记事本等应用程序创建的文件,以查看文件的样子。您会注意到该文件的内容不是可理解的,因为写进程将信息转换为更易为计算机使用的格式。 

'===========================================================


C# Source:  CS\ReadWrite.aspx    
VB Source:  VB\ReadWrite.aspx    

<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.IO" %>

<script language="VB" runat=server>

Class TestBinary

    Public Shared Function ReadFile(selection As String) As String
        Dim output As StringBuilder = New StringBuilder()

        Dim fs As FileStream = New FileStream("data.bin", FileMode.OpenOrCreate)
        Dim r As BinaryReader = New BinaryReader(fs)

        Try
            r.BaseStream.Seek(0,SeekOrigin.Begin)    ' 将文件指针设置到文件开始

            ' 因为不同数据类型之间的很多转换结果都是不可解释的,
            ' 所以当在其他类型与二进制数据之间进行转换时,
            ' 必须捕捉可能引发的任何潜在的异常...
            ' 能够正确读取数据依赖于如何写入信息...
            ' 这与写日志文件时不同。
            Do While r.BaseStream.Position < r.BaseStream.Length       '  当未到达文件结尾时

                Select Case selection

                Case "Boolean"
                    output.Append( r.ReadBoolean().ToString() )

                Case "String"
                    output.Append( r.ReadString() )

                Case "Integer"
                    output.Append( r.ReadInt32().ToString() )
                End Select
            Loop
        Finally
            fs.Close()
        End Try

        return output.ToString()
    End Function

    Public Shared Function WriteFile(output As Object, selection As String) As String
        Dim fs As FileStream = New FileStream("data.bin", FileMode.Create)
        Dim w As BinaryWriter = New BinaryWriter(fs)
        Dim strOutput As String = ""

        w.BaseStream.Seek(0, SeekOrigin.End)        '  将文件指针设置到文件结尾

        ' 因为我们正在写的信息可能不适合于所选择用于写入的特定样式
        ' (例如,单词“Hello”作为整数?),所以我们必须捕捉写入
        ' 错误,并通知用户未能执行该任务
        Try
            Select Case selection

            Case "Boolean"
                Dim b As Boolean = Convert.ToBoolean(output)
                w.Write( b )

            Case "String"
                Dim s As String = Convert.ToString(output)
                w.Write( s )

            Case "Integer"
                Dim i As Int32 = Convert.ToInt32(output)
                w.Write(i)
            End Select

        Catch E As Exception
            ' 让用户知道未能写入该信息
            strOutput = "写异常:" & chr(13) & _
                "无法以所请求的格式写入要写入的信息。" & _
                chr(13) & "请输入尝试写入的数据类型的有效值"
        End Try

        fs.Close()

        return strOutput
    End Function
End Class

Sub btnAction_Click(src As Object, E As EventArgs)

    Dim s As String = ""

    ' 写出文件
    s = TestBinary.WriteFile(txtInput.Text, lstDataIn.SelectedItem.Text)

    If s = "" Then
        Try
            ' 读回信息,显示信息...
            txtOutput.Text = TestBinary.ReadFile(lstDataIn.SelectedItem.Text)
        Catch Exc As Exception
            ' 让用户知道未能写入信息 
            s = "读异常:" & chr(13) & _
                "无法以所请求的格式读取要写入的信息。" & _
                chr(13) & "请输入尝试写入的数据类型的有效值"

        End Try

    Else
        txtOutput.Text = s
    End If
End Sub
</script>

<html>
<head>
 
          <link rel="stylesheet" href="intro.css">
</head>

<body style="background-color:f6e4c6">
<form method=post runat="server">
<p>

<table>
<tr>
    <td><b>
下面的示例使用 BinaryWriter 对象创建一个二进制文件,然后使用 BinaryReader 读取该信息。</b>可以选择不同的对象来将所需的信息写入文件

此演示用于强调您需要知道如何读取已写入的二进制文件。一旦以某种格式写入数据,就只能以该格式读取该信息。但是,可以将多种不同的数据类型写入文件。在此演示中,输入任意字符串并将它们作为字符串读取,对于整型,仅输入整型数值项(试试浮点数字,然后看看会发生什么...);对于布尔型项,仅输入词“false”和“true”。
<p>
    <hr>
    </td>
</tr>
</table>

<asp:Table id="basetable" runat="server" border="0" cellspacing="0" cellpadding="5">

<asp:tablerow>
      <asp:tablecell verticalalign="top">
    请选择要保存到二进制文件的数据类型...
      </asp:tablecell>
      <asp:tablecell verticalalign="top">
    <asp:listbox id="lstDataIn" runat="server">
      <asp:listitem>Boolean</asp:listitem>
      <asp:listitem selected="true">String</asp:listitem>
      <asp:listitem>Integer</asp:listitem>
    </asp:listbox>
      </asp:tablecell>

      <asp:tablecell verticalalign="top">
    <asp:button id="btnAction" οnclick="btnAction_Click" Text="写入/读取文件" runat="server"/>
      </asp:tablecell>
</asp:tablerow>

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在VB.NET中,我们可以使用不同的方法读写数据文件读取数据文件: - 使用StreamReader类,我们可以打开一个数据文件并逐行读取其中的数据。首先,我们需要创建一个StreamReader对象并使用OpenText方法打开数据文件。然后,使用ReadLine方法来读取一行数据,并将数据存储在变量中。通过重复这个过程,我们可以读取文件中的所有数据。最后,我们需要使用Close方法关闭文件。 写入数据文件: - 使用StreamWriter类,我们可以打开一个数据文件并将数据写入其中。首先,我们需要创建一个StreamWriter对象并使用CreateText方法创建新文件或使用AppendText方法打开已存在的文件。然后,我们可以使用WriteLine方法向文件中写入一行数据,或使用Write方法向文件中写入指定的内容。通过重复这个过程,我们可以向文件中写入所需的数据。最后,我们需要使用Close方法关闭文件。 此外,还有其他数据文件读写的方式可供选择: - 使用BinaryReader和BinaryWriter类,可以读写二进制文件。 - 使用File类的ReadAllText和WriteAllText方法,可以一次性读取或写入整个文件的内容。 无论使用哪种方法,我们需要注意的是要正确处理文件操作期间可能发生的异常。为此,我们可以使用Try-Catch语句来捕获和处理可能的异常,以确保程序的稳定性和可靠性。 总之,在VB.NET中,有多种方法可供选择读写数据文件,我们可以根据自己的需求和偏好来选择最合适的方法。 ### 回答2: 在VB.NET中,可以使用输入输出流来读写数据文件。 对于数据文件读取,首先需要创建一个文件输入流(FileInputStream)或者文本读取器(TextReader),打开需要读取文件。然后,通过循环读取数据流或者逐行读取文本的方式,从文件中逐个读取数据,并将其存储到变量或者集合中。 例如,可以使用StreamReader类来读取文本文件。可以使用下面的代码片段来演示如何读取一个文本文件: ``` Dim filePath As String = "C:\data.txt" ' 此处为文件路径 Dim line As String Using reader As New StreamReader(filePath) Do While reader.Peek() >= 0 line = reader.ReadLine() ' 在此处处理读取的数据 Console.WriteLine(line) Loop reader.Close() End Using ``` 对于数据文件的写入,同样需要创建一个文件输出流(FileOutputStream)或者文本编写器(TextWriter),打开需要写入的文件。然后,通过将数据逐个写入数据流或者逐行写入文本的方式,将其写入到文件中。 例如,可以使用StreamWriter类来写入文本文件。可以使用下面的代码片段来演示如何写入一个文本文件: ``` Dim filePath As String = "C:\data.txt" ' 此处为文件路径 Using writer As New StreamWriter(filePath) writer.WriteLine("Hello, world!") ' 在此处写入更多数据 writer.Close() End Using ``` 需要注意的是,在读写数据文件时,要确保文件路径的正确性,并且进行异常处理,以处理可能的读写错误或者文件不存在的情况。 ### 回答3: VB.NET提供了很多用于读写数据文件的功能和方法。 对于文本文件读写,可以使用StreamReader和StreamWriter类来实现。StreamReader类提供了ReadLine和ReadToEnd方法用于读取文本文件的内容,而StreamWriter类提供了Write和WriteLine方法用于写入文本到文件中。使用这两个类的实例,我们可以很方便地读取和写入文本文件的数据。 对于二进制文件读写,可以使用BinaryReader和BinaryWriter类来实现。BinaryReader类提供了Read和ReadString等方法用于读取二进制文件的内容,而BinaryWriter类提供了Write和WriteString等方法用于写入数据到二进制文件中。使用这两个类的实例,我们可以读取和写入任何形式的二进制数据。 另外,VB.NET还提供了一些其他的类和方法来处理数据库文件读写。例如,可以使用OleDbDataReader和OleDbCommand类来从数据库中读取数据,使用OleDbCommand类和ExecuteNonQuery方法来执行SQL语句更新数据库中的数据。 在读写数据文件的过程中,我们还可以使用异常处理机制来处理可能出现的错误。例如,可以使用Try-Catch语句来捕获可能抛出的异常,并根据需要采取相应的处理措施,比如显示错误消息或回滚已进行的操作。 总之,通过VB.NET提供的各种类和方法,我们可以方便地实现数据文件读写操作。无论是文本文件二进制文件,还是数据库文件,都可以通过适当的类和方法来进行读取和写入操作,并在必要时进行异常处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值