Saturday, November 5, 2011

Read and Write Text File in Visual Basic .Net


While were on the subject of the new file functions, lets take a short digression and quickly discuss how to write to and read from files using the new .NET Framework methods. You can still use the existing Visual Basic file functions, but the .NET Framework file methods, although a little more complicated, offer more flexibility when working with files.
Well create a simple console application that creates a file, writes Hello World to it, closes the file, and then reopens it and shows the contents in a message box.
Sub Main()
   '* Create a file and write to it
   Dim outFile As System.IO.FileStream
   outFile = New System.IO.FileStream("C:tempFile.txt", _
      IO.FileMode.Create, IO.FileAccess.Write)
   Dim fileWriter As New System.IO.StreamWriter(outFile)
   fileWriter.WriteLine("Hello World")
   fileWriter.Close()
   outFile.Close()

   '* Open a file and read from it
   Dim inFile As System.IO.FileStream
   inFile = New System.IO.FileStream("C:tempFile.txt", _
      IO.FileMode.Open, IO.FileAccess.Read)
   Dim fileReader As New System.IO.StreamReader(inFile)
   While fileReader.Peek > -1
      MsgBox(fileReader.ReadLine)
   End While
   fileReader.Close()
   inFile.Close()
 End Sub

To open a file for writing, you have to perform two steps: create a stream object and then create a StreamWriter object to write to the stream. You can then write to the file using the StreamWriter objects Write and WriteLine methods. Reading from a file involves a similar process: create a stream object, and then create a StreamReader to read from the stream. To determine whether there is anything to read from the file, use the StreamReader objects Peek method, which returns the value of the next byte in the file, or 1 if there is nothing left to read. The StreamReader objects Read, ReadBlock, ReadLine, and ReadToEndmethods are used to read the contents of the file.

No comments:

Post a Comment