File.OpenWrite Method In VB.NET

This article explains how to open a file for writing.
  • 3621

File.OpenWrite Method

The OpenWrite method opens a file for writing. If file does not exist, it creates a new file and opens if for writing. The OpenWrite method takes a file name as parameter and returns a FileStream object on the specified file.

Dim fs As FileStream = fi.OpenWrite()

Once we have a FileStream object, we can use its Write method to write to the file. The WriteMethod takes a byte array. The following code snippet creates a byte array and passes it to the Write method of the FileStream.

Dim info As [Byte]() = New UTF8Encoding(True).GetBytes("New File using OpenWrite Method " & vbLf)

fs.Write(info, 0, info.Length)
 

The following lists the complete code sample.

 

Imports System.Text

Imports System.IO

Module Module1

    Sub Main()

        Dim fileName As String = "C:\Temp\MaheshTXFITx.txt"

        Dim fi As New IO.FileInfo(fileName)

        ' If file does not exist, create file

        If Not fi.Exists Then

            'Create the file.

            Using fs As FileStream = fi.Create()

                Dim info As [Byte]() = New UTF8Encoding(True).GetBytes("File Start")

                fs.Write(info, 0, info.Length)

            End Using

        End If

        Try

            ' Open a file and add some contents to it

            Using fs As FileStream = fi.OpenWrite()

                Dim info As [Byte]() = New UTF8Encoding(True).GetBytes("New File using OpenWrite Method " & vbLf)

                fs.Write(info, 0, info.Length)

                info = New UTF8Encoding(True).GetBytes("----------START------------------------ " & vbLf)

                fs.Write(info, 0, info.Length)

                info = New UTF8Encoding(True).GetBytes("Author: Mahesh Chand " & vbLf)

                fs.Write(info, 0, info.Length)

                info = New UTF8Encoding(True).GetBytes("Book: ADO.NET Programming using C#" & vbLf)

                fs.Write(info, 0, info.Length)

                info = New UTF8Encoding(True).GetBytes("----------END------------------------")

                fs.Write(info, 0, info.Length)

            End Using

            ' Read file contents and display on the console

            Using fs As FileStream = File.OpenRead(fileName)

                Dim byteArray As Byte() = New Byte(1023) {}

                Dim fileContent As New UTF8Encoding(True)

                While fs.Read(byteArray, 0, byteArray.Length) > 0

                    Console.WriteLine(fileContent.GetString(byteArray))

                End While

            End Using

        Catch Ex As Exception

            Console.WriteLine(Ex.ToString())

        End Try

     End Sub

End Module

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.