File.Open Method In VB.NET

In thsi article I describe how to open a file using VB.NET
  • 14886

Read and Write a File

Open a File

A File must be opened using an IO resource before it can be read or write to. A file can be opened to read and/or write purpose. The FileInfo class provides four methods to open a file.

• Open
OpenRead
OpenText
OpenWrite

File.Open Method

The Open method opens a FileStream on the specified file in the specified file mode.

Dim fs As FileStream = fi.Open(FileMode.Open, FileAccess.Write)

Here is 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

            Using fs As FileStream = fi.Open(FileMode.Open, FileAccess.Write)

                Dim info As [Byte]() = New UTF8Encoding(True).GetBytes("Add more text")

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

            End Using

        Catch Ex As Exception

            Console.WriteLine(Ex.ToString())

        End Try

    End Sub

End Module

 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.