File类用于VB.NET中的File操作。我们可以创建,删除,复制等操作。
如何创建文件?
为了创建一个新的File,我们可以在File类中调用Create方法。
语法:File.Create(FilePath)
FilePath:新文件对象的名称
File.Create(“ c: testFile.txt”)
如何检查文件是否存在?
在创建File对象之前,我们通常会检查File是否存在。为此,我们在File类中使用Exists方法。
语法:File.Exists(FilePath)为布尔值
FilePath:文件名
布尔值:返回true或false;如果File存在,则返回true;否则返回false
VB.NET:File.Exists(“ c: testFile.txt”)
以下VB.NET源代码显示了这些操作:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If File.Exists("c:estFile.txt") Then
'shows message if testFile exist
MsgBox("File 'testFile' Exist ")
Else
'create the file testFile.txt
File.Create("c:estFile.txt")
MsgBox("File 'testFile' created ")
End If
End Sub
End Class
当执行此源代码时,它首先检查File是否存在,如果存在则表明消息文件存在,否则创建一个新的File Object。
如何复制文件?
如果要复制文件对象,可以在File类中使用Copy方法。
语法:Copy(sourceFileName,destFileName)
sourceFileName:我们要移动的源文件。
destFileName:目标文件名。
VB.NET:File.Copy(“ c: testFile.txt”,“ c: testDir testFile.txt”)
如何删除文件对象?
当我们要删除文件对象时,可以使用File类中的Delete方法。
语法:Delete(FilePath)
DirPath:要删除的文件对象。
VB.NET:File.Delete(“ c: testDir testFile.txt”)
以下VB.NET源代码显示了这些操作:
Imports System.IOPublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click If Not File.Exists("c:estFile.txt") Then MsgBox("文件不存在 ") Else File.Copy("c:estFile.txt", "c:estDirestFile.txt") MsgBox("复制文件成功 ") File.Delete("c:estFile.txt") MsgBox("删除文件成功") End If End SubEnd Class
![60f6cf6e92a26a4302a7ab0d6d707179.png](https://i-blog.csdnimg.cn/blog_migrate/977ca203bff65a15c6ba33de9264d592.jpeg)
Imports System.IOPublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click If Not File.Exists("c:estFile.txt") Then MsgBox("文件不存在 ") Else File.Copy("c:estFile.txt", "c:estDirestFile.txt") MsgBox("复制文件成功 ") File.Delete("c:estFile.txt") MsgBox("删除文件成功") End If End SubEnd Class