這個範例會使用 Create 類別中的 File 方法,在指定的路徑上建立空的文本檔。
範例
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使用變數來寫入檔案。
健全的程式設計
如果檔案已經存在,則會加以取代。
以下條件可能會造成例外狀況:
路徑名稱的格式不正確。 例如,它包含不合法的字元,或只是空格符 (ArgumentException)。
路徑是唯讀的(IOException)。
路徑名稱為
Nothing(ArgumentNullException)。路徑名稱太長(PathTooLongException)。
路徑無效(DirectoryNotFoundException)。
路徑只是冒號 “:” (NotSupportedException)。
.NET Framework 安全性
SecurityException 可能會在部分信任環境中拋出。
要呼叫 Create 方法需要 FileIOPermission。
UnauthorizedAccessException如果使用者沒有建立檔案的許可權,則會擲回 。