File Access
[ Using VB ]
File access can be a powerful tool to use. Most file access done in visual basic programs would be accessing .INI files. These files are helpful for storing user settings, high scores on a game, etc.
The basic things you need to know are:
Opening Files (Input and Output)
Reading and Writing
Files
Closing Files
Open pathname For mode As [#]filenumber
This is the basic syntax you want to use for most data access. pathname is the path of the file enclosed in quotation marks (" "). Mode can either be input, output, or append. Filenumber is the number you will use in the rest of the code to access that file.
2 Basic Modes:
Input - The input mode is used to read files. Whenever you're getting data from a file, use input. For example: You could open a file to read the high scores for a game. See the example at the bottom of the page (or click Here).
Output - The output mode is what you open a file as if you are going to write to it.
When reading the parts of a file, you can use these keywords:
Input - Used as Input(Number, Filenumber) where Number is the number of characters to return. (ex: Input(15, #1))
Input # - Used as "Input #Filenumber, Variable(s)". The Variable or Variables is/are the variable(s) you want to store the inputted text in. (Ex: Input #1, strInput) Use this one whenever the file was written with Write #.
Line Input # - Line Input #Filenumber, Variable. This statement reads a single line from the open file. It reads from files that were written with the Print # statement. Variable is the variable you want to save the inputted text to.
When writing to a file, you can use these keywords:
Print # - Print #Filenumber, Output. The output is what you want to write to a file. Files written with Print # should be read with Line Input # or Input.
Write # - Write #Filenumber, Output. The output is the string you want to write to the file. Files written with Write # are best read with Input #.
One import thing to remember is that every time you open a file, you need to close it. If you leave a file open, it can be corrupted and may be totally different the next time you try and open it. To do this, just type Close filenumber. For example:
Dim strInput As String, intInput2 As Integer
Open "c:\windows\HighScor.ini" For Input As 1 'Open File
For i = 0 To 9 'Get the top 10 scores
Input #1, strInput1, intInput2
lblName(i) = strInput1 'Display them in labels
lblScore(i) = intInput2
Next i
Close 1 'Close the file!!
The file this example is reading was written with Write #, therefore it's being read with Input #. The file looks like:
"Name #1",100
"Name #2",200
"Name #3",300
"Name #4",400
"Name #5",500
"Name #6",600
"Name #7",700
"Name #8",800
"Name #9",900
"Name #10",1000