A common task when creating a form based windows application is to allow a user to save their information and to also load saved information. In this short tutorial I will show you the basic steps to save a form’s information to a file and then load up the contents of the saved file.

Saving a Form’s Data to a File

The process for saving data to a file is pretty straightforward in Visual Basic. They include opening up a writer to a specified file, writing the contents, and then closing the writer when completed.

  1. Define and open your File Writer
    In this case we will utilize the StreamWriter class of the System.IO package. I will assume for these instructions that you have imported the System.IO library.
    Dim FileWriter As StreamWriter ' define the stream writer
    
    ' Open the File for writing
    FileWriter = New StreamWriter("c:\temp\sampleFile.txt", False)
  2. Write the desired data to the file
    To write data to the file you can utilize the WriteLine function. In the case of forms you may want to write different data. For a text field saving the Text is appropriate while when using a check box or radio button you will want to save the Checked property.
     ' Save Component values
    FileWriter.WriteLine(textBox.Name & "|" & textBox.Text)
    FileWriter.WriteLine(comboBox.Name & "|" & comboBox.SelectedIndex.ToString())
    FileWriter.WriteLine(radioBtn.Name & "|" & radioBtn.Checked.ToString())
  3. Close and Save your data to the File
    To complete your write you simply need to call Close on your writer. However if you want you can first call Flush to have the data written out. This step is optional however as the Close function will call Flush if needed.
     ' Save and Close File
    FileWriter.Flush() ' optional as close will flush
    FileWriter.Close()

Reading Data from a File

The process for reading information out of a File is similar to the writing process. First you want to open up the file, then you want to read a line of data, single character, or etc depending on how you are going to process the data until you reach the end. After you have read all the data you would lastly close the File.

  1. Define and open your File Reader
    In this case we will utilize the StreamReader class of the System.IO package.
     Dim FileReader As StreamReader   ' define the File Reader
    FileReader = New StreamReader("c:\temp\sampleFile.txt", False)
  2. Iterate until the End of File is reached
    Do Until FileReader.EndOfStream
        ' Processing Code goes here
    Loop
  3. Read in and Process the File’s data
    In the below example we will read in the file’s contents 1 line at a time. To see the full example of how the data is processed please view the full source code below.
    'Read the next line
    prop = FileReader.ReadLine()
  4. Close the File Reader
    After the loop close the FileReader as all the data has been read.
    FileReader.Close()

A complete sample Save and Write Class

For those that learn better by example below is a Simple Class that holds a complete example of saving data to a File from a Form in addition to loading the saved data from the form and setting the components to the correct state. The example contains basic error checking including validating that the saved file exists, however it does not validate the data in the file is of the correct format and not corrupted.

Imports System.IO
 
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        loadSavedData()
    End Sub
 
    Private Sub CloseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseButton.Click
        Close() 'Close Application
    End Sub
 
    Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click
        loadSavedData()
    End Sub
 
    Private Sub loadSavedData()
 
        Dim FileReader As StreamReader   ' define the File Reader
        Dim prop(2) As String            ' define array of length 2

        ' Test if the Saved File exists
        If File.Exists("c:\temp\sampleFile.txt") Then
 
            'Open the File for reading
            FileReader = New StreamReader("c:\temp\sampleFile.txt", False)
 
            ' Continue until EOF reached
            Do Until FileReader.EndOfStream
 
                'Read the next line and split its value based on the | character
                prop = FileReader.ReadLine().Split("|")
 
                ' If TextBox Component set it's property
                If String.Equals(prop(0), textBox.Name) Then
 
                    textBox.Text = prop(1)
 
                    ' If ComboBox Component set it's property
                ElseIf String.Equals(prop(0), comboBox.Name) Then
 
                    comboBox.SelectedIndex = Integer.Parse(prop(1))
 
                    ' If RadioButton set if checked
                ElseIf String.Equals(prop(0), radioBtn.Name) Then
 
                    radioBtn.Checked = Boolean.Parse(prop(1))
 
                ElseIf String.Equals(prop(0), RadioButton1.Name) Then
 
                    RadioButton1.Checked = Boolean.Parse(prop(1))
 
                ElseIf String.Equals(prop(0), RadioButton2.Name) Then
 
                    RadioButton2.Checked = Boolean.Parse(prop(1))
 
                End If
 
            Loop
 
            ' close the file
            FileReader.Close()
 
        End If
 
    End Sub
 
    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
 
        Dim FileWriter As StreamWriter ' define the stream writer

        ' Open the File for writing
        FileWriter = New StreamWriter("c:\temp\sampleFile.txt", False)
 
        ' Save Component values
        FileWriter.WriteLine(textBox.Name & "|" & textBox.Text)
        FileWriter.WriteLine(comboBox.Name & "|" & comboBox.SelectedIndex.ToString())
        FileWriter.WriteLine(radioBtn.Name & "|" & radioBtn.Checked.ToString())
        FileWriter.WriteLine(RadioButton1.Name & "|" & RadioButton1.Checked.ToString())
        FileWriter.WriteLine(RadioButton2.Name & "|" & RadioButton2.Checked.ToString())
 
        ' Save and Close File
        FileWriter.Flush() ' optional as close will flush
        FileWriter.Close()
    End Sub
End Class
, , , , , , , ,

Ever wonder how you can persist data for a user in your Flash SWF applications? The simple answer is to use a local SharedObject or as it is commonly known the Flash Cookie. These objects are stored to the users local machine much like a cookie with it’s access limited to current domain and optional path, allowing you to save data that can be shared between different SWFs on your site if you so desire.

Shared Objects storage on the local computer

The Shared Object is stored in an .sol file on the users local computer. These files are stored in the Flash Player directory of the users profile and much like cookies are accessible only to by SWFs with the same domain and local path. The default size limitation for a .sol file is usually around 100Kb however this can be modified by the user and if more space is required they will have to approve it. Don’t worry to much about that part right now we’ll touch on that later.

Obtaining a Shared Object

To create or obtain an existing Shared Object we utilize the getLocal method. This method returns the Shared Object with the given name and path for the domain. If for some reason the Shared Object could not be created then an error will be thrown, some possible reasons for this would be that 3rd party storage is disabled.

Understanding the getLocal function

The getLocal function takes up to 3 parameters with only the name being required.

  • name: The identifier of the Shared Object
  • localPath: The full or partial path to the swf that determines where it is stored locally. By setting this to a generic path that is used by multiple swfs in your domain you can have saved data from one swf be read and used by another swf.
  • secure: Boolean identifying if the SWF is accessible only over HTTPS. If true then an HTTP request to the SWF will not allow the Shared Object to be created or read from. (default value is FALSE)

To create/obtain a Shared Object with a specified name you would use the following code:

try {
    var sharedObj:SharedObject = SharedObject.getLocal( "user_settings" );
} catch(e:Error) {
    // Shared Object could not be created
}

If we wanted to create/obtain a Shared Object that had a defined localPath and was accessible only by HTTPS then we would use the following code:

try {
    var sharedObj:SharedObject = SharedObject.getLocal( "user_settings", "/shared/", true );
} catch(e:Error) {
    // Shared Object could not be created
}

Reading and Writing data to the Shared Object

Now that you have instantiated your local Shared Object you will want to store and read that data you wish to persist across usages of your SWF application. Access of the data stored in the Shared Object is done through the data property. You simply specify the named property and set a value to it or output it into another variable or parameter.

To illustrate lets assume we want to save the Users high score into the Shared Object.

sharedObj.data.high_score = 1000;

If we wanted to read the saved high_score value then we simply would access it the same way:

var highScore = sharedObj.data.high_score;

Write Immediately with Flush

When the SWF application quits or exits is when the Shared Object would normally get written to the local file system. However if you want to save your data immediately you can utilize the flush method. This method will cause the data to be written immediately. If the write could not be performed an error will be thrown, or if the size of the Shared Object is above the the users defined maximum size then they will be presented with a dialog box to confirm/deny the additional space. If this occurs then a pending status will be returned and you will need to listen for a netStatus event to determine if the save was successful. Please note that the dialog boxes minimum size is 215 x 138 and your SWF will need to be larger then this to display the full dialog box.

Sample basic example

try {
    var status:String = sharedObj.flush();
    if( status == SharedObjectFlushStatus.FLUSHED ) {
        // Successfull
    }
} catch(e:Error) {
    // Shared Object could not be saved
}

If your Shared Object has a maximum size that it can grow to you can pass this value to the flush value. What this does is make it so that Flash will ask for the inputted amount of space so that it doesn’t ask with each save as the size of the Shared Object increases.

try {
    var status:String = sharedObj.flush( 4096 );
    if( status == SharedObjectFlushStatus.FLUSHED ) {
        // Successful
    }
} catch(e:Error) {
    // Shared Object could not be saved
}

Erasing your Shared Object

To delete your Shared Object you utilize the clear method. When called it empties the data in your SharedObject instance and will also delete the file saved on the user’s local computer.

sharedObj.clear();

Saving user data in Flash is a relatively simply task. Although you may not utilize them in all applications they can come in handy with games and user settings. Allowing you to present the user with a consistent experience in that application as well as other applications in that domain.

Resources

, , , , , , , , , ,