[ 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
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
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: