CanOz Blog

Neil Knobbe's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

AprMay 2013Jun
SMTWTFS
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Archives

Image Galleries

vbCity Blogs

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:

 

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:

 

Dim sr As New StreamReader(PathToFileHere)

 

' or

 

Dim sr As StreamReader

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

 

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

 

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

 

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

 

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

 

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

 

Read a File Line by Line

 

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

 

Dim sr As StreamReader  ' Declare the StreamReader

 

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

 

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).

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

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

Loop

 

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.
posted on Monday, November 28, 2005 7:43 PM