Visual Basic 9 (2008)Visual Basic 8 (2005)Visual Studio 2008Visual Studio 2005.NET 2.0.NET 3.5中级Visual Studio.NETVisual Basic
在 Visual Basic 2008 中将自定义结构写入二进制文件






4.08/5 (6投票s)
将用 Visual Basic 2008 编写的自定义数据类型写入二进制文件的技术。
引言
在本文中,我想向您展示如何将 Visual Basic 结构的內容写入二进制文件。 这很有用,因为 .NET Framework 暴露的各种方法(如 FileStream
、BinaryWriter
和 My
对象)只能将属于 基础类库 的数据类型写入二进制文件。
那么,解决方案是什么? 我们可以序列化结构并将序列化的对象写入二进制文件。
使用代码
首先,打开 Visual Studio 2008 并创建一个新的 Visual Basic 2008 控制台应用程序。 我们可以有一个非常简单的 Structure
,名为 Software
,其中包含有关计算机程序的信息
Module Module1
<serializable() /> Structure Software
Dim programName As String
Dim productionYear As Integer
Dim programProducer As String
End Structure
Sub MakeBinaryFile()
Dim Program As Software
Program.programProducer = "Microsoft"
Program.programName = "Windows Vista"
Program.productionYear = 2006
下一步是序列化结构。 我们可以实现一个方法来完成此操作。 这里,我指定了一个预定的文件名,但通常并非如此。 以下代码中的注释应该有所帮助
'Retrieves a BinaryFormatter object and
'instantiates a new Memorystream to which
'associates the above BinaryFormatter, then writes
'the content to a binary file via My namespace
Dim BF As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim MS As New System.IO.MemoryStream()
'Serialization is first in memory,
'then written to the binary file
BF.Serialize(MS, Program)
My.Computer.FileSystem.WriteAllBytes("c:\temp\programs.bin", MS.GetBuffer(), False)
最后,我们可以读取回我们的二进制文件,以检查一切是否正常工作。 以下代码片段可以完成此操作
'Verifies that deserializing works fine and shows
'the result in the Console window.
Dim bytes As Byte() = My.Computer.FileSystem.ReadAllBytes("c:\temp\programmi.bin")
Program = DirectCast(BF.Deserialize(New System.IO.MemoryStream(bytes)), Software)
Console.WriteLine(Program.programName + " produced by " + _
Program.programProducer + " in the Year " + _
Program.productionYear.ToString)
Console.ReadLine()
End Sub
我们只需要以以下方式在 Sub Main
中调用我们的方法
Sub Main()
MakeBinaryFile()
End Sub
关注点
对于像上面这样简单的结构,代码可能看起来用处不大。 但您必须考虑到结构可以包含任何类型的 .NET 对象(例如:流)。
此外,对象序列化在读取/写入方面提供了良好的性能水平。