尽管计算机上的文件可以不同的类型和文件存储,但是,二进制格式是文件的较常用格式之一。此处对创建二进制文件的简短介绍使用基类 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>