如何:在 Visual Basic 中建立檔案
這個範例會使用 File 類別 (Class) 中的 Create 方法,在指定的路徑建立空的文字檔。
範例
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
編譯程式碼
請使用 file 變數寫入至檔案。
穩固程式設計
如果檔案已存在,則會取代該檔案。
下列情形可能會造成例外狀況 (Exception):
路徑名稱錯誤。 例如,它包含不合法的字元或只是泛空白字元 (ArgumentException)。
路徑是唯讀的 (IOException)。
路徑名稱是 Nothing (ArgumentNullException)。
路徑名稱太長 (PathTooLongException)。
路徑無效 (DirectoryNotFoundException)。
路徑只是冒號 ":" (NotSupportedException)。
安全性
在部分信任的環境下可能會擲回 SecurityException。
呼叫 Create 方法時需要 FileIOPermission。
如果使用者沒有建立檔案的權限,則會擲回 UnauthorizedAccessException。