Xtreme Visual Basic Talk

Xtreme Visual Basic Talk (http://www.xtremevbtalk.com/)
-   Tutors' Corner (http://www.xtremevbtalk.com/tutors-corner/)
-   -   File I/O In VB.Net (http://www.xtremevbtalk.com/tutors-corner/148864-file-vb-net.html)

MikeJ 02-28-2004 09:47 PM

File I/O In VB.Net
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 class.

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)

FileMode Constants
The FileMode constants have pretty much the same function as their Legacy VB6 counterparts, but they have changed their names in .Net.

FileMode.Append 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.
FileMode.Create 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.
FileMode.CreateNew This tells the system to make a new file. If the path already exists, an error will occur.
FileMode.Open This tells the system that it should open an existing file.
FileMode.OpenOrCreate This tells the system that it should open the file if it exists. If it doesn't exist, a new file will be created.
FileMode.Truncate This tells the system that it should open an existing file and clear its contents.

Here is the MSDN link for these constants:

FileAccess Constants
These constants are responsible for telling the system how to handle the access modes.

FileAccess.Read With the Read access mode, data can be read from the file. This will make the file ReadOnly.
FileAccess.ReadWrite With this access mode, you can write data to the file, and read from the file. This would be the normal access mode.
FileAccess.Write This access mode means you can write to the file.

Here is the MSDN link for these constants:

FileShare Constants
These constants will tell the system how to let other FileStreams access your file.

FileShare.None Any request to open the file by another application will fail until the file is closed.
FileShare.Read This lets successive openings of your file for reading.
FileShare.ReadWrite This lets successive openings of your file for reading and writing.
FileShare.Write 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 Try 'We have our variables, lets attempt to open it myFileStream = New System.IO.FileStream(sFileName, _ FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite) Catch '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.") Finally '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 myFileStream.Close() End If End Try End Sub
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.

MikeJ 02-28-2004 09:49 PM

1 Attachment(s)
FileStreams in .Net: Part 2 Reading From A File Stream

As we saw in Part 1, we can use the FileStream to open a file. This is useful up to a point, but if you want to read from it, we can use a StreamReader. You can use a stream reader class to access your file based on what the file contains. The simplest one is StreamReader, and it works with textual information and can be used to read from a text file.

You declare a StreamReader like any other variable. You need to use the New keyword with a StreamReader and you need to pass an instance of a FileStream to it.

After creating the reader, you can call the Read method to get one character out of the stream. The Read method will return the next available character from the stream as an Integer and moves to the current position of the next character in line. It will return -1 if it has reached the end of the buffer. The ReadLine method will read a line out of the file, return it as a string, and will go to the next line. The ReadToEnd method gets all of the datat from the current position all the way to the end of the file, and will return a String.

The Peek method takes a character from the current position, but doesn't advance to the next position. It will return a value of -1 if the stream contains no more data. This method is good to check if the end of the file has been reached without extracting any data out of it.

The BaseStream property gives a reference to the stream associated with the reader. Also, always use the Close() method when you are done reading from the file to release resources.
Private Sub btnReadFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReadFile.Click 'Declare any variables Dim sFileName As String = Application.StartupPath & "\VB.txt" Dim myFileStream As New System.IO.FileStream(sFileName, _ FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read) 'Create the StreamReader and associate the filestream with it Dim myReader As New System.IO.StreamReader(myFileStream) 'Read the entire text, and set it to a string Dim sFileContents As String = myReader.ReadToEnd() 'Print it to the textbox txtFileDisplay.Text = sFileContents 'Close everything when you are finished myReader.Close() myFileStream.Close() End Sub
We have opened the file that we created in Part 1, and have displayed the contents inside of the textbox called txtFileDisplay. However, the textbox is empty because we haven't written to the file yet.

FileStreams in .Net: Part 3 Writing To A File Stream

We can now open and read from a file. While these two methods are important in the File I/O world, without a doubt the most important part remains. As a developer you will probably need to write to a file in some way shape or form. Different stream writers can be used depending on the type of data that you need to write. The StreamWriter is a way to write plain text to a file. (For information on BinaryWriter, check out this page in MSDN).

As with the other members of System.IO, you need to declare the variable with the New keyword. Also, pass an instance of a file stream to it.

After it has been initialized, the Write method of the StreamWriter writes a Char, Char array, or a String to the stream, but won't move to the next line. The variable is passed in as the only parameter. The WriteLine method does the same thing, but it will automatically add a new line to the stream.

When you use the Write or WriteLine method, the stream updates in memory only. The Flush method writes any new data stored in the stream to the file. If the data needs to move to the file immediately after calling Write or WriteLine, you can set the AutoFlush property to True.

The Close method will close the connection to the file and will free up the resources from the memory related to writing. In case you forget to Flush to the file, it will automatically flush to the file before closing.
Private Sub btnWriteFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnWriteFile.Click 'Declare those variables! Dim sFileName As String = Application.StartupPath & "\VB.txt" Dim myFileStream As New System.IO.FileStream(sFileName, _ FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None) 'Create the stream writer Dim myWriter As New System.IO.StreamWriter(myFileStream) 'Write in what is in the text box myWriter.WriteLine(txtFileDisplay.Text) 'Flush before we close myWriter.Flush() 'Close everything myWriter.Close() myFileStream.Close() 'Clear the text txtFileDisplay.Text = "" End Sub
In this example, we have created the file, if it doesn't exist, and then wrote whatever was in the textbox to it.

I will probably update this tutorial some more, particularly with BinaryWriter and other ways to create files, and how to do files other than plain text files. Also, I'd like to thank Bucky with his technical revision of Part 1, and again would like to point out that MSDN is where I found most of the information found in this tutorial. If you have any questions, feel free to contact me through PM, IRC, or MSN.

All times are GMT -6. The time now is 05:17 PM.

Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2018, vBulletin Solutions, Inc.
Search Engine Optimisation provided by DragonByte SEO v2.0.15 (Lite) - vBulletin Mods & Addons Copyright © 2018 DragonByte Technologies Ltd.
All site content is protected by the Digital Millenium Act of 1998. Copyright©2001-2011 MAS Media Inc. and Extreme Visual Basic Forum. All rights reserved.
You may not copy or reproduce any portion of this site without written consent.