Read and write the text file using vb.net

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 vb.net 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.

Public
Sub FileHandler() 
   Try 
      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) 
         Else 
            write.Write(rd + vbCrLf) 
          End If 
       Next 
        read.Close() 
         write.Close()
Catch ex As Exception 
      Throw
End Try
End Sub


Similar Articles