此示例使用 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。