Browse DevX
Sign up for e-mail newsletters from DevX


Take Advantage of Streams and Formatters in VB.NET  : Page 5

.NET File I/O operations use Stream and Formatter classes that abstract many tasks you had to code manually in classic VB.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

In the last section of the article you'll find code prototypes for the file operations you're likely to use most frequently. The simplest, and most common, operation is moving text in and out of text files. Binary files are not commonly used to store individual values; instead, modern applications most often use them to store objects, collections of objects, and other machine-readable data. In the following sections you'll find code examples for each of these scenarios.

Writing and Reading Text Files
To save text to a file, create a StreamReader object based on a FileStream object for the specific file and then call its Write method passing the text to be written to the file as argument. The following statements prompt the user to specify a file name with a SaveFileDialog instance, and then write the contents of the TextBox1 control to the selected file:

Example: Saving Text to a File

SaveFileDialog1.Filter = _ "Text Files|*.txt|All Files|*.*" SaveFileDialog1.FilterIndex = 0 If SaveFileDialog1.ShowDialog = DialogResult.OK Then Dim FS As FileStream = SaveFileDialog1.OpenFile Dim SW As New StreamWriter(FS) SW.Write(TextBox1.Text) SW.Close() FS.Close() End If

To read a text file and display it on a TextBox control, use a similar set of statements and call the ReadToEnd method of a StreamReader object. This method will read the entire file and return its contents as a string:

Example: Reading Text from a File

OpenFileDialog1.Filter = _ "Text Files|*.txt|All Files|*.*" OpenFileDialog1.FilterIndex = 0 If OpenFileDialog1.ShowDialog = DialogResult.OK Then Dim FS As FileStream FS = OpenFileDialog1.OpenFile Dim SR As New StreamReader(FS) TextBox1.Text = SR.ReadToEnd SR.Close() FS.Close() End If

Persisting Objects
You can serialize individual objects in binary form with the BinaryFormatter class, or as XML-formatted text with the SoapFormatter class. If you replace all references to the BinaryFormatter class with reference to the SoapFormatter class, you can serialize objects in XML without making any other changes to the code.

Start by creating an instance of the BinaryFormatter class:

Dim BinFormatter As New Binary.BinaryFormatter()

Then create a FileStream instance based on the file where you want to serialize the object:

Dim FS As New System.IO.FileStream("c:\test.txt", IO.FileMode.Create)

After creating the BinFormatter and the FS variables, call the Serialize method to serialize any serializable framework object:

R = New Rectangle(rnd.Next(0, 100), _ rnd.Next(0, 300), rnd.Next(10, 40), _ rnd.Next(1, 9)) BinFormatter.Serialize(FS, R)

To serialize your own objects, add the Serializable attribute to the class:

Example: A Simple Serializable Class

<Serializable()> Public Structure Person Dim Name As String Dim Age As Integer Dim Income As Decimal End Structure

To serialize an instance of the Person class, create an instance of the class and initialize it. Then serialize the Person object by creating a formatter and calling its Serialize method:

Example: Serializing a Custom Object using the BinaryFormatter Class

P = New Person() P.Name = "Joe Doe" P.Age = 35 P.Income = 28500 BinFormatter.Serialize(FS, P)

You can continue serializing additional objects serialized on the same stream, and then later read them back in the same order. For example, to serialize a Rectangle object immediately after the Person object in the same stream, use a statement like this:

BinFormatter.Serialize(FS, New Rectangle _ (0, 0, 100, 200))

To deserialize the Person object, create a BinaryFormatter object, call its Deserialize method and then cast the method's return value to the appropriate type. The Deserialize method deserializes the next available object in the stream.

Suppose you've serialized a Person and a Rectangle object, in that order. To deserialize them, open the FileStream for reading, and use the following statements:

Example: Deserializing Custom Objects

Dim P As New Person() P = BinFormatter.Serialize(FS, Person) Dim R As New Rectangle R = BinFormatter.Serialize(FS, Rectangle)

Persisting Collections
Most applications deal with collections of objects rather than individual object variables. To work with sets of data, you can create an array (or any other collection, such as an ArrayList or a HashTable), populate it with objects and then serialize the entire collection with a single call to the Serialize method. The following statements create an ArrayList with two Person objects and serialize the entire collection:

Example: Persisting a Collection of Custom Objects

Dim FS As New System.IO.FileStream _ ("c:\test.txt", IO.FileMode.Create) Dim BinFormatter As New Binary.BinaryFormatter() Dim P As New Person() Dim Persons As New ArrayList P = New Person() P.Name = "Person 1" P.Age = 35 P.Income = 32000 Persons.Add(P) P = New Person() P.Name = "Person 2" P.Age = 50 P.Income = 72000 Persons.Add(P) BinFormatter.Serialize(FS, Persons)

To read the instances of the Person class you've stored to a file, create an instance of the BinaryFormatter class and call its Deserialize method, passing a FileStream object that represents the file as an argument. The Deserialize method returns an Object variable, which you can cast to the appropriate type. The following statements deserialize all the objects persisted in a file and process the objects of the Person type:

Example: Deserializing Custom Objects

FS = New System.IO.FileStream _ ("c:\test.txt", IO.FileMode.OpenOrCreate) Dim obj As Object Dim P As Person(), R As Rectangle() Do obj = BinFormatter.Deserialize(FS) If obj.GetType Is GetType(Person) Then P = CType(obj, Person) ' Process the P objext End If Loop While FS.Position < FS.Length - 1 FS.Close()

To deserialize an entire collection call the Deserialize method and then cast the method's return value to the appropriate type. The following statements deserialize the Persons array:

Example: Deserializing a Collection of Custom Objects

FS = New System.IO.FileStream("c:\test.txt", IO.FileMode.OpenOrCreate) Dim obj As Object Dim Persons As New ArrayList obj = CType(BinFormatter.Deserialize(FS), ArrayList) FS.Close()

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date