如何:在 Visual Basic 中建立檔案

這個範例會在 File 類別中使用 Create 方法,以在指定的路徑中建立空白文字檔。

範例

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

編譯程式碼

使用 file 變數,以寫入檔案。

穩固程式設計

如果檔案已存在,則會予以取代。

以下條件可能會造成例外狀況:

.NET Framework 安全性

在部分信任環境中,可能會擲回 SecurityException

Create 方法呼叫需要 FileIOPermission

如果使用者無權建立檔案,則會擲回 UnauthorizedAccessException

另請參閱