Export (0) Print
Expand All

How to: Create a File in Visual Basic

This example creates an empty text file at the specified path using the Create method in the File class.

Imports System
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim path As String = "c:\temp\MyTest.txt" 

        ' Create or overwrite the file. 
        Dim fs As FileStream = File.Create(path)

        ' Add text to the file. 
        Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
        fs.Write(info, 0, info.Length)
        fs.Close()
    End Sub 

End Module

Use the file variable to write to the file.

If the file already exists, it is replaced.

The following conditions may cause an exception:

A SecurityException may be thrown in partial-trust environments.

The call to the Create method requires FileIOPermission.

An UnauthorizedAccessException is thrown if the user does not have permission to create the file.

Show:
© 2014 Microsoft