View Single Post
Old 02-28-2004, 09:49 PM
MikeJ's Avatar
MikeJ MikeJ is offline

Retired Moderator
* Expert *
Join Date: Sep 2002
Location: Austin, Texas
Posts: 6,747

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.
Attached Files
File Type: zip (7.3 KB, 534 views)
{ Lex Fori } { Locus Classicus } { Rutilus Scrinium }
Osculare pultem meam!

Last edited by John; 03-01-2004 at 12:54 PM. Reason: adjusted code formatting
Reply With Quote