共用方式為


Walkthrough: Persisting an Object in Visual Basic 

Although you can set an object's properties to default values at design time, any values entered at run time are lost when the object is destroyed. You can use serialization in Visual Basic to persist an object's data between instances, allowing you to store values and retrieve them the next time the object is instantiated.

When storing simple data, such as a name or number, you can use the My.Settings object. For more information, see My.Settings Object.

In this walkthrough, you will create a simple Loan object and persist its data to a file, then retrieve the data from the file when you recreate the object. You will then modify the code to persist the object in a SOAP format.

Security noteSecurity Note

This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create permission for the folder. Permissions are set using access control lists. If the file already exists, the application needs only Write permission, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read privileges to a single file (rather than Create privileges for a folder). Also, it is more secure to write data to user folders than to the root folder or the Program Files folder.

Security noteSecurity Note

This example stores data in a binary or SOAP format file. These formats should not be used for sensitive data, such as passwords or credit card information.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

Creating the Loan Object

The first step is to create a Loan class and a test application that uses the class.

To create the Loan class

  1. Create a new Class Library project and name it "LoanClass". For more information, see How to: Create Solutions and Projects.

  2. In the Code Editor, change the name of the class from "Class1" to "Loan".

  3. Add the following public members to the class:

    Public LoanAmount As Double = 10000.0
    Public InterestRate As Double = 7.5
    Public Term As Integer = 36
    Public Customer As String
    

You will also need to create a simple application that uses the Loan class.

To create a test application

  1. From the File menu, add a Windows Application project to your solution by pointing to Add and then clicking New Project.

  2. In the Add New Project dialog box, enter LoanApp as the name of the project, and click OK to close the dialog box.

  3. In Solution Explorer, select the LoanApp project.

  4. On the Project menu, click Set as StartUp Project.

  5. On the Project menu, click Add Reference.

  6. In the Add Reference dialog box, click the Projects tab and select the LoanClass project.

  7. Click OK to close the dialog box.

  8. In the designer, add four TextBox controls to the form.

  9. In the Code Editor, add the following code:

    Private TestLoan As New LoanClass.Loan
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
    System.EventArgs) Handles MyBase.Load
        TextBox1.Text = TestLoan.LoanAmount.ToString
        TextBox2.Text = TestLoan.InterestRate.ToString
        TextBox3.Text = TestLoan.Term.ToString
        TextBox4.Text = TestLoan.Customer
    End Sub
    

At this point, you can build and run the application. Note that the default values from the Loan class appear in the text boxes. Try changing the interest-rate value from 7.5 to 7.1, then close the application and run it again—the value reverts to the default of 7.5.

In the real world, interest rates change periodically, but not necessarily every time the application is run. Rather than making the user update the interest rate each time the application is run, it would be better to preserve the most recent interest rate between instances of the application. In the next step, you will do just that by adding serialization to the Loan class.

Using Serialization to Persist the Object

In order to persist the values for the Loan class, you must first mark the class with the Serializable attribute.

To mark a class as serializable

  • Change the class declaration for the Loan class as follows:

    <Serializable()> Public Class Loan
    

The Serializable attribute tells the compiler that everything within the class can be persisted to a file. In this case, you want to persist only the InterestRate member, but you probably do not want to persist the Customer, LoanAmount, or Period members. The NonSerialized attribute can be used to mark class members that should not be persisted. For simplicity in this example, everything except the Customer member is persisted.

To prevent a member from being serialized

  • Change the declaration for the Customer member as follows:

    <NonSerialized()> Public Customer As String
    

The next step is to add the serialization code to the LoanApp application. In order to serialize the class and write it to a file, you will use the System.IO and System.Xml.Serialization namespaces. To avoid typing the fully qualified names, you can use the Imports statement.

To add references to namespaces

  • Add the following Imports statements to the top of the Form1 class:

    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    

    In this case, you are using a binary formatter to save the object in a binary format. Later in this walkthrough, you will modify the code to save the object in a SOAP format.

The next step is to add code to deserialize the object from the file when the object is created.

To deserialize an object

  1. Add a constant to the class for the serialized data's file name.

    Const FileName As String = "SavedLoan.bin"
    
  2. Modify the code in the Form1_Load event procedure as follows:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
    System.EventArgs) Handles MyBase.Load
        If File.Exists(FileName) Then
            Dim TestFileStream As Stream = File.OpenRead(FileName)
            Dim deserializer As New BinaryFormatter
            TestLoan = CType(deserializer.Deserialize(TestFileStream), LoanClass.Loan)
            TestFileStream.Close()
        End If
        TextBox1.Text = TestLoan.LoanAmount.ToString
        TextBox2.Text = TestLoan.InterestRate.ToString
        TextBox3.Text = TestLoan.Term.ToString
        TextBox4.Text = TestLoan.Customer
    End Sub
    

    Note that you first need to check that the file exists. If it exists, create a Stream class to read the binary file and a BinaryFormatter class to translate the file. The CType method is used to convert from the stream to the Loan object type.

Next you need to add code to save the data entered in the text boxes to the Loan class, and then you need to serialize the class to a file.

To save the data and serialize the class

  • Add the following code to the Form1_Closing event procedure:

    Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As _
    System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        TestLoan.LoanAmount = CType(TextBox1.Text, Double)
        TestLoan.InterestRate = CType(TextBox2.Text, Double)
        TestLoan.Term = CType(TextBox3.Text, Integer)
        TestLoan.Customer = TextBox4.Text
    
        Dim TestFileStream As Stream = File.Create(FileName)
        Dim serializer As New BinaryFormatter
        serializer.Serialize(TestFileStream, TestLoan)
        TestFileStream.Close()
    End Sub
    

At this point, you can once again build and run the application. Initially the default values appear in the text boxes. Try changing the values and entering a name in the fourth text box. Close the application and then run it again. Note that the new values now appear in the text boxes, except for the customer name that was marked as NonSerialized.

Persisting the Object Using a SOAP Format

The example so far has demonstrated how to persist an object to a text file using a binary format. A binary format is fine for most Windows applications. For Web applications or XML Web services, you may want to persist the object to an XML file using a SOAP format, which makes the object easy to share.

In order to persist the object to a SOAP format, you must first reference the SoapFormatter class. The SoapFormatter class resides in its own namespace: System.Runtime.Serialization.Formatters.Soap.

To persist the object using SOAP format

  1. In Solution Explorer, select the LoanApp project.

  2. On the Project menu, click Add Reference.

  3. In the Add Reference dialog box, click the .NET tab and select the System.Runtime.Serialization.Formatters.Soap component.

  4. Click OK to close the dialog box.

  5. In the Code Editor, add an Imports statement to the top of the Form1 module:

    Imports System.Runtime.Serialization.Formatters.Soap
    
  6. Change the file name from SavedLoan.bin to SavedLoan.xml.

  7. In the Form1_Load event procedure, change the Dim statement from Dim deserializer As New BinaryFormatter to:

    Dim deserializer As New SoapFormatter
    
  8. In the Form1_Closing event procedure, change the Dim statement from Dim serializer As New BinaryFormatter to:

    Dim serializer As New SoapFormatter
    

At this point, you can build and test the application. When you first run the application, the SavedLoan.xml file is created. You can view this file by choosing the Show All Files option in Solution Explorer; it will be in the Bin node for the Windows Application project.

Note

If you are already in Show All Files mode, you need to refresh the view by choosing Refresh from the View menu in order to see the file.

Note that the three members of the LoanClass are displayed in XML format. Try changing the InterestRate value in the XML file, then save it and run the application again. The new interest rate appears in the second text box.

See Also

Concepts

PropertyBag Equivalents for Visual Basic 6.0 Users
Basics of .NET Framework Serialization