Wednesday, September 8, 2010

Reading and Writing to Text Files

Today we will write "Hello World" to a file and then read it from there and display it to the Console

First, open Visual Studio, make a new VB Console Application and add System.IO namespace to your sollution.

To write the text file, create an instance of StreamWriter class and provide the path as a parameter such as 

"C:\Hello World.txt". The following code demonstrates this:

Dim sw As StreamWriter = New StreamWriter("C:\Hello World.txt") 

Now, we will write code to write in the text file using the write method:

sw.Write("Hello, World!")

Now, close the the text file :

sw.Flush()
sw.Close()

_____________________________________________________

To read the text file, create an instance of StreamReader class and provide the path of the text file as a parameter. The following code demonstrates this:

Dim sr As StreamReader = New StreamReader("C:\Hello World.txt") 

Now, we will write code to read from the text file using the ReadtoEnd method:

Console.Writeline(sr.ReadToEnd())

Now, close the the text file :

sr.Close()

If you like my post please follow my blog.

No comments:

Share the Knowledge

My Card