Tutorial 06: Reading and Writing Data

April 18, 2008

© NS BASIC Corporation. All rights reserved.

Contributed by Tom Newman, Mission Peak Designs


Contents:

  1. Introduction
  2. Getting Started
  3. Creating the Form
  4. Creating the Code
  5. Writing String Data
  6. Reading String Data
  7. Testing the Program

Introduction

The purpose of this tutorial is to demonstrate reading and writing data to a file using NS Basic/Desktop. You should have completed Tutorial #1 before beginning this tutorial.

The program to be developed uses NewObject's ActiveX Storage and File control to create, write, and read files. This tutorial will create a program that writes and reads string data to a file.

Getting Started

Including file reading/writing support in your application requires adding the NewObjects ActiveX control to the desktop. The control is automatically installed when you installed NS Basic/Desktop but you will need to install it on systems where NS Basic/Desktop is not installed.

(For a complete reference on the methods above, make sure you read the Tech Note 08: File I/O Control - SFStream and Tech Note 08a: File I/O Control with Fields - SFRecord)

Creating the Form

Start a new "Standard" project and save it as FileIO.nsd

Create the following controls on the form:

The form should look like the following:

Creating the Code

First off we will create code that initializes our program and creates and deletes our test file.

Enter the following code in the Code Window (you can copy and paste this code):

Now let's analyze the code, line by line:

Writing String Data

Next we will create code that writes 1000 records (strings) to our test file.

Now let's analyze the code, line by line:

Reading String Data

Next we will create code that reads 1000 records (strings) from our test file and follow that up by code that reads 1000 random records.

Now let's analyze the code, line by line:

Testing the Program

Press F5 to save and start the program. Your results should look similar to the image below. The program creates a file (MyFile.txt) and writes/reads 1000 strings. The last button deletes the file.