Appending data to an existing file in VB.NET

In this article we will learn how to append data to an existing file.

Here I am using FileStream object to write contents to a file.
First a FileSteam and File object is created. Using file object we will compare wether file is exists are not.
If file exits in the disk then we will truncate it otherwise we will create new file and allow that file for read and write using file steam object.

If file already exists then we will open that file in append mode.
Then we will point the stream reader to last line using streamwriter.
Example :
sw.BaseStream.Seek(0, SeekOrigin.End)

If file does't exists then we will create new file and open that file in create mode.
Then we will point the stream reader to first line using streamwriter.
Example: sw.BaseStream.Seek(0, SeekOrigin.Begin)

Public Sub ExportToFile(ByVal oFileName As String, ByVal myContent As String)
        Dim file As FileStream
        Dim f As IO.File

        If (f.Exists(oFileName)) Then
            file = New FileStream(FileToWrite, FileMode.Append, FileAccess.Write)
            file = New FileStream(FileToWrite, FileMode.Create, FileAccess.ReadWrite)
        End If

        Dim sw As New StreamWriter(file, System.Text.Encoding.Default)
        If (f.Exists(oFileName)) Then
            sw.BaseStream.Seek(0, SeekOrigin.End)
            sw.BaseStream.Seek(0, SeekOrigin.Begin)
        End If


    End Sub

By Cos mos   Popularity  (10050 Views)