Wednesday, 18 January 2012

File handling in VB.Net

Append data to 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)
        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

To create file and write to it using FileStream 


Public Sub WriteErrorReport(ByVal message As String, ByVal FileName As String)
Dim f As File
Dim fstream As FileStream
If f.Exists(FileName) Then
            fstream = New FileStream(FileName, FileMode.Truncate, FileAccess.ReadWrite)
Else
            fstream = New FileStream(FileName, FileMode.Create, FileAccess.ReadWrite)
End If
Dim sWriter As New StreamWriter(fstream)
sWriter.BaseStream.Seek(0, SeekOrigin.Begin)
sWriter.Write(message)
sWriter.Close()
End Sub

No comments:

Post a Comment