Sweet idea to begin a FAQ!
And I'm willing to contribute... I want to change the Topic Title to "File Access in VB.NET" if you're ok with that ofcourse :)
File Access in VB.NET
You might be wondering why the Open statement doesn't work in VB.NET, and you're wondering how to handle files? You came at the right spot!
The thing is, the File functions are given a more logical name, for example the Open statement is changed to FileOpen, and yes, Close has been changed to FileClose... easy right?
What to expect in this small tutorial?
- A short introduction to the different file modes in VB.NET
- Sequential mode
- Random mode
- Binary mode
- FreeFile
- Other File Functions
- The System.IO Namespace
Short Introduction
First of all, let me explain what types of file modes exist in VB.NET, well actually the same as in VB6:
- Sequential access (Input, Output, and Append modes) is used for writing text files, such as error logs and reports.
- Random access (Random mode) is used to read and write data to a file without closing it. Random-access files keep data in records, which makes it easy to locate information quickly.
- Binary access (Binary mode) is used to read or write to any byte position in a file, such as storing or displaying a bitmap image.
Sequential Files
Here's an example on how to Open a textfile and write to it, and later read the textfile in and show the contents of the file in a MessageBox
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\test.txt"
Dim sTmp As String
FileOpen(1, sTxtFile, OpenMode.Output)
Print(1, "This is a file test!")
FileClose(1)
FileOpen(1, sTxtFile, OpenMode.Input)
Input(1, sTmp)
FileClose(1)
MessageBox.Show(sTmp) 'Returns "This is a file test!"
End Sub
So essentialy it's quite the same as in VB6 and shouldn't give too much trouble finding out what all the parameters mean.
Also the LineInput statement still works as expected:
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\test.txt"
Dim sTmp As String
FileOpen(1, sTxtFile, OpenMode.Input)
Do While Not EOF(1)
MessageBox.Show(LineInput(1))
Loop
FileClose(1)
End Sub
Random Access
Random mode can be quite handy to handle structures in files for example.
In this example I used a Structure that represents a Member of the Vbworldforums, how they would be stored in a file using Random Access.
You might notice the <VBFixedString(15)>, this is how the current VB.NET handles Fixed strings, but I believe that is subject to change, and this tutorial will be updated as neccesary.
VB Code:
Structure VbWorldMember
Public lNumberOfPosts As Long
<VBFixedString(15)> Public sFirstName As String 'This sample won't work if the name is longer than 15, change as needed...
<VBFixedString(15)> Public sLastName As String
<VBFixedString(15)> Public sNickname As String
<VBFixedString(15)> Public sRank As String
End Structure
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\testrandom.dat"
Dim sTmp As String
Dim JohnDoe As VbWorldMember 'Declare a new VbWorldMember called JohnDoe
JohnDoe.lNumberOfPosts = 4
JohnDoe.sFirstName = "John"
JohnDoe.sLastName = "Doe"
JohnDoe.sNickname = "JD"
JohnDoe.sRank = "Newbie"
FileOpen(1, sTxtFile, OpenMode.Random, , , Len(JohnDoe))
FilePut(1, JohnDoe, 1) 'Put the JohnDoe Structure in the first record of the file
FileClose(1)
Dim dummyJohnDoe As VbWorldMember 'Make a dummy JohnDoe to test if we can get the old JohnDoe
FileOpen(1, sTxtFile, OpenMode.Random)
FileGet(1, dummyJohnDoe, 1) 'Get the first record of the file in the NewJohnDoe structure
FileClose(1)
'Show the number of posts for the dummyJohnDoe which we imported from the Random File.
MessageBox.Show(dummyJohnDoe.lNumberOfPosts) 'Returns "4"
End Sub
Binary Access
Binary Access is used for handling files at byte-level, this is used for example Bmp files, but can you be used for text also.
It also can be used as in the Random Access, but this file mode doesn't require fixed-length strings, so keeps the filesize smaller than with Random Mode.
This is an example how to read write text to a file using binary access.
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\testbinary.dat"
FileOpen(1, sTxtFile, OpenMode.Binary)
FilePut(1, "Binary file test!")
FileClose(1)
FileOpen(1, sTxtFile, OpenMode.Binary)
Dim sTmp As New String(" ", LOF(1)) 'Make the buffer as large as the file to make sure the contents of the file fit in the buffer.
FileGet(1, sTmp)
FileClose(1)
MessageBox.Show(sTmp) 'returns "Binary file test!"
End Sub
This is an example if you want to get, for example, only the first 3 bytes of a file.
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\testbinary.dat"
FileOpen(1, sTxtFile, OpenMode.Binary)
FilePut(1, "Binary file test!")
FileClose(1)
FileOpen(1, sTxtFile, OpenMode.Binary)
Dim sTmp As New String(" ", 3) 'Make the 3 bytes long, so we'll only get 3 bytes...
FileGet(1, sTmp) 'with the Byte Number omitted we'll start reading from the beginning
FileClose(1)
MessageBox.Show(sTmp) 'returns "Bin"
End Sub
Now what if you want only byte 4 to 6?
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "c:\testbinary.dat"
FileOpen(1, sTxtFile, OpenMode.Binary)
FilePut(1, "Binary file test!")
FileClose(1)
FileOpen(1, sTxtFile, OpenMode.Binary)
Dim sTmp As New String(" ", 3) 'Make the 3 bytes long, so we'll only get 3 bytes...
FileGet(1, sTmp, 4) 'By setting the Byte number to 4, we'll start from the 4th byte instead of the 1st.
FileClose(1)
MessageBox.Show(sTmp) 'Returns "ary"
End Sub
FreeFile
The use of FreeFile still is the same as in VB6:
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sTxtFile As String = "e:\jop\test.txt"
Dim iFF As Integer = FreeFile()
Dim sTmp As String
FileOpen(iFF, sTxtFile, OpenMode.Input)
Input(iFF, sTmp)
FileClose(iFF)
MessageBox.Show(sTmp)
End Sub
Other File Functions
All of the old functions still exist in VB.NET:
- Dir
- EOF
- FileCopy
- FileDateTime
- FileLen
- FreeFile
- GetAttr
- Loc
- LOF
- Seek
- SetAttr
What? Where is the Move Function!!!
(jeez I was wondering that too!)
There is a function called: Rename, which actually works the same like the old Move function:
VB Code:
Rename("c:\oldfile.txt", "c:\newfile.txt")
But I found out that it returns an error when you try to change the extension of the file;
VB Code:
Rename("c:\oldfile.txt", "c:\newfile.html") 'Returns an error!
So what to do? Well I'll discuss that in the next topic.
The System.IO Namespace
The System.IO contains loads of classes that will make solving your Input/Output problems a lot easier!
In the example above we discussed the use of Rename, it won't let us rename the file extension, here is where the System.IO comes into action!
VB Code:
'To import the System.IO namespace:
Imports System.IO
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The following code will is actually in the System.IO namespace:
File.Move("c:\oldfile.txt", "c:\newfile.html") 'will now work!!!
End Sub
There are a lot more functions in the System.IO.File namespace that you'll want to explore, check MSDN and look on the Internet for more examples!