Reader Level:

Read and write the text file using

Posted by Sunil Atkari Articles | C# Language July 31, 2009
The code snippet in this article shows how to read and write text files in VB.NET.
  • 0
  • 0
  • 23067

Here I have created a console application. It will help you to read and write a text file using file handling concepts of VB.NET.

If you want to use file handling concept of then you have to import System.IO Namespace. Basically Namespace is logical group of types. In this case we are importing IO related features.

In below code, first I have created one new text file. After that I have read another text file then doing some process means writing 80 characters in each and every line of another text file, which was created. The record length of each and every line will be 80 characters.

Sub FileHandler() 
      Dim strf As String = "WriteFile.log" 
      Dim fws As New FileStream(strf, FileMode.Create, FileAccess.Write) 
      Dim write As StreamWriter 
      write =
New StreamWriter(fws) 
      Dim strfile As String = "ReadFile.log" 
      Dim text As String = Nothing 
      Dim fs As New FileStream(strfile, FileMode.Open, FileAccess.ReadWrite) 
      Dim read As StreamReader 
      read =
New StreamReader(fs) 
      read.BaseStream.Seek(0, SeekOrigin.Begin) 
      Dim rd As String = Nothing 
      While (read.Peek() > -1) 
         text = Trim(read.ReadToEnd()) 
      End While 
      _textCount = Len(text) 
      Dim _count As Integer = 0 
      Dim i As Integer = 0 
      For i = 1 To text.Length 
         rd = Mid(text, i, 80) 
         _count = _count + 80 
          i = i + 79 
         write.BaseStream.Seek(0, SeekOrigin.End) 
         If _count = _textCount Or _count > _textCount Then 
            write.Write(rd + vbCrLf) 
          End If 
Catch ex As Exception 
End Try
End Sub


Trending up