How to write to a text file in VB.NET

This code sample shows how to write to a text file in C#.
  • 3295
Download Files:
 

We can StreamWriter class to write to a file. The Write method is used to write to a text file.

In the StreamWriter constructor, the first parameter is the file name and second parameter is optional, boolean type. If second parameter is true, an existing file will be appended with new text. Otherwise it will erase old text and start with new text.

 

Module Module1

 

    Sub Main()

 

 

        Dim fileName As String = "C:\Mahesh\McTextFile.txt"

        Using reader As New System.IO.StreamReader(fileName)

            While Not reader.ReadLine() Is Nothing

                Console.WriteLine(reader.ReadLine())

            End While

        End Using

 

        Try

            Using writer As New System.IO.StreamWriter(fileName, True)

                writer.WriteLine("New text")

                writer.WriteLine("New text line goes here")

            End Using

        Catch ex As Exception

 

        End Try

 

        Console.ReadKey()

 

    End Sub

 

End Module

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.