/Home /Archive /Syndicate /Blog /Support /About /Contact  
All Visual Basic Feeds in one place!





Reading Files

Depending on your Project you could find yourself needing to read Files. One way that you can accomplish this is to use the StreamReader. StreamReader is part of the System.IO Namespace and you must add the Imports Statement to your Project before you can access the StreamReader. At the very top of your Form.vb code page, before anything else, you would type:
 

    1 Imports System.IO


Now your Project can access the System.IO Namespace. (Admittedly you could access the System.IO Namespace without using the Imports Statement. You would just need to put System.IO in front of all the Classes of the IO Namespace that you use in your Project. For example System.IO.StreamReader or System.IO.File.OpenText, but I prefer using the Imports Statement.)
 
The next thing you want to do is to declare your StreamReader. A couple different ways of doing this are:
 

    1         Dim sr As New StreamReader(PathToFileHere)

    2 

    3         ' or

    4 

    5         Dim sr As StreamReader

    6         sr = File.OpenText(PathToFileHere)


 
Depending on what you want to do with the contents of the File, you can Read the contents of the File Line by Line or the entire Length of the File.
 
Read entire Length of a File
 

    1         Imports System.IO  ' Add Imports Statement to top of Form Code

    2 

    3         Dim sr As New StreamReader(PathToFileHere)  ' Declare the StreamReader and Open the File

    4 

    5         Dim MyString As String  ' Declare a String Variable to hold the contents of the File.

    6 

    7         MyString = sr.ReadToEnd()  ' Read the contents of the file into the String Varaible

    8 

    9         txtTextBox1.Text = MyString  ' Display the contents of the File.


 
Read a File Line by Line
 

    1         Imports System.IO  ' Add Imports Statement to top of Form Code

    2 

    3         Dim sr As StreamReader  ' Declare the StreamReader

    4 

    5         sr = File.OpenText(PathToFileHere)  ' Open the File

    6 

    7         Do While sr.Peek <> -1  ' While Peek can read Characters from the File (Peek Returns the next Character until there are no more then will Return a -1).

    8             sr.ReadLine() ' Read the next Line of the File

    9             txtTextBox1.Text &= sr.ReadLine & Environment.NewLine ' Display the Line of the File

   10         Loop

   11 

   12         sr.Close()


 
As with just about everything in programming there are several different ways to accomplish a task.  These are just two ways that you can go about reading the contents of Files.

 

© 2005 Serge Baranovsky. All rights reserved.
All feed content is property of original publisher. Designated trademarks and brands are the property of their respective owners.

This site is maintained by SubMain(), a division of vbCity.com, LLC