Search This Blog

Tuesday, February 15, 2011

Adding data to an existing file using 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)

The code follows :

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)
Else
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)
Else
sw.BaseStream.Seek(0, SeekOrigin.Begin)
End If

sw.Write(myContent)

sw.Close()

End Sub

No comments:

Post a Comment