FileStreams in .Net: Part 1 - Opening A File Stream
For Parts 1-3 of this tutorial you will need:
- A textbox named txtFileDisplay
- 3 buttons, named btnOpenFile, btnReadFile, btnWriteFile
- VB.Net 2002 or newer
Also, in all these examples, be sure to have imported System.IO.
Many programs allow you to save and load user's files. Others use files to store settings for the program. In VB.Net we can open or create new files using the FileStream class. The aim of this tutorial is to provide a quick overview of some of the most frequently used parts of the FileStream
What is FileStream?
A FileStream normally cannot access its contents. Separate reader and writer classes exist to access the FileStream. To create a file stream, declare the stream like any other variable. The type is System.IO.FileStream. To initialize the variable properly, you need to include the New keyword. This will call a constructor inside of the class which will set up the variable for you to use it.
A standard FileStream constructor will need the name of the file you wish to open or create, the access mode, the access level, and the sharing mode. [example: FileStream(path, mode, access, share) ]. The FileMode constant determines how the stream will open or create the file. The FileShare constant will determine if other applications can read or write to the file when your application opens it. (Note – Be sure to use the Close method to close the stream when you finish with it.)
With VB.Net you can lock portions of the file from being accessed by other programs. Use the Lock method to do this. Lock accepts two parameters, the starting position and the number of bytes following the starting position to lock. The Unlock method accepts the same two parameters but, as the name mentions, it returns access to the area instead.
(See the MSDN article here
The FileMode constants have pretty much the same function as their Legacy VB6 counterparts, but they have changed their names in .Net.
– While this name hasn't changed from Legacy VB, its function is a little different. It opens the file, and if it exists, it goes to the end of the file. If the file doesn't exist, it will create a new file. This will only work with the FileAccess constant FileAccess.Write.
– This does what you might think; it tells the operating system that it should create a new file. If the file exists, it will overwrite the file that exists.
– This tells the system to make a new file. If the path already exists, an error will occur.
– This tells the system that it should open an existing file.
– This tells the system that it should open the file if it exists. If it doesn't exist, a new file will be created.
– This tells the system that it should open an existing file and clear its contents.
Here is the MSDN link for these constants:
These constants are responsible for telling the system how to handle the access modes.
– With the Read access mode, data can be read from the file. This will make the file ReadOnly.
– With this access mode, you can write data to the file, and read from the file. This would be the normal access mode.
– This access mode means you can write to the file.
Here is the MSDN link for these constants:
These constants will tell the system how to let other FileStreams access your file.
– Any request to open the file by another application will fail until the file is closed.
– This lets successive openings of your file for reading.
– This lets successive openings of your file for reading and writing.
– This lets successive openings of your file for writing.
Here is the MSDN file for these constants:
Opening A File Stream
Well, enough of the explanations, lets get down to the code. For this first file, lets open the file VB.txt which I've included in the source for this tutorial for Read Only, but let other programs read and write to this file while we are using it. (Notice how we are using error handling. It's not entirely necessary, as we will open the file with a mode of OpenOrCreate, so it will create itself anyways, but it's useful when you aren't using this method.)
Private Sub btnOpenFile_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles btnOpenFile.Click
'The variables that we will need
Dim sFileName As String = Application.StartupPath & "\VB.txt"
Dim myFileStream As System.IO.FileStream
'We have our variables, lets attempt to open it
myFileStream = New System.IO.FileStream(sFileName, _
FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)
'Make sure that it exists, and if it doesn't display an error
MessageBox.Show("Count not open the file. Make sure '" & FileName & _
"' exists in the location shown.")
'It works, but we are going to try one last method
If myFileStream.CanRead = True Then
'This is where we would read from the file
txtFileDisplay.Text = "File opened!"
'We are done with the file now, so close it
We now have a new file that is empty. It exists in our startup folder, which is our application's file, and if you run this in Debug mode, it is in the bin folder. We aren't reading or writing to it, so it just exists.