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" %>