'从文件指定位置读取数据 dim fn as new io.filestream(e:\123.mp3, IO.FileMode.Open) dim fr as new io.binaryreader(fn) fr.BaseStream.Position = 1000 '从1000字节处开始读取文件 dim data() as byte= fr.ReadBytes(2000) '读取2000个字节至data()数组 fr.close fn.close
'在文件指定位置写入数据 dim fn as new io.filestream(e:\123.mp3, IO.FileMode.Open) dim fr as new io.binarywriter(fn) fr.BaseStream.Position = 1000 '从1000字节处开始读取文件 fr.write(data) '将data数组写入文件 fr.close fn.close
%@ 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