VB.NET語言經(jīng)過長時(shí)間的發(fā)展,很多用戶都很了解VB.NET語言了,這里我發(fā)表一個(gè)關(guān)于VB.Net語言 復(fù)制、刪除文件的例子,和大家一起分享一下。
VB.Net語言 復(fù)制、刪除文件代碼:
- Imports System.IO
- Imports System.IO.Directory
- ' ======================================================
- ' 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容copy到目標(biāo)文件夾下面
- ' 如果目標(biāo)文件夾為只讀屬性就會報(bào)錯(cuò)。
- ' ======================================================
- Public Shared Sub CopyDir(ByVal srcPath As String, ByVal aimPath As String)
- Try
- ' 檢查目標(biāo)目錄是否以目錄分割字符\結(jié)束,如果不是則添加之
- If aimPath(aimPath.Length - 1) <> Path.DirectorySeparatorChar Then
- aimPath += Path.DirectorySeparatorChar
- End If
- '判斷源目錄是否存在,不存在則退出.
- If (Not Directory.Exists(srcPath)) Then Exit Sub
- ' 判斷目標(biāo)目錄是否存在如果不存在則新建之
- If (Not Directory.Exists(aimPath)) Then Directory.CreateDirectory(aimPath)
- ' 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
- ' 如果你指向copy目標(biāo)文件下面的文件而不包含目錄請使用下面的方法
- ' string[] fileList = Directory.GetFiles(srcPath);
- Dim fileList() As String = Directory.GetFileSystemEntries(srcPath)
- ' 遍歷所有的文件和目錄
- For Each FileName As String In fileList
- ' 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸Copy該目錄下面的文件
- If Directory.Exists(FileName) Then
- CopyDir(FileName, aimPath + Path.GetFileName(FileName))
- ' 否則直接Copy文件
- Else
- File.Copy(FileName, aimPath + Path.GetFileName(FileName), True)
- End If
- Next
- Catch ex As Exception
- MessageBox.Show(ex.ToString())
- End Try
- End Sub
- ' ======================================================
- ' 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容Detele
- ' 測試的時(shí)候要小心*作,刪除之后無法恢復(fù)。
- ' ======================================================
- Public Shared Sub DeleteDir(ByVal aimPath As String)
- Try
- ' 檢查目標(biāo)目錄是否以目錄分割字符結(jié)束如果不是則添加之
- If (aimPath(aimPath.Length - 1) <> Path.DirectorySeparatorChar) Then
- aimPath += Path.DirectorySeparatorChar
- End If
- '判斷待刪除的目錄是否存在,不存在則退出.
- If (Not Directory.Exists(aimPath)) Then Exit Sub
- ' 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
- ' 如果你指向Delete目標(biāo)文件下面的文件而不包含目錄請使用下面的方法
- ' string[] fileList = Directory.GetFiles(aimPath);
- Dim fileList() As String = Directory.GetFileSystemEntries(aimPath)
- ' 遍歷所有的文件和目錄
- For Each FileName As String In fileList
- If (Directory.Exists(FileName)) Then
- ' 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸Delete該目錄下面的文件
- DeleteDir(aimPath + Path.GetFileName(FileName))
- Else
- ' 否則直接Delete文件
- File.Delete(aimPath + Path.GetFileName(FileName))
- End If
- Next
- '刪除文件夾
- System.IO.Directory.Delete(aimPath, True)
- Catch ex As Exception
- MessageBox.Show(ex.ToString())
- End Try
- End Sub
【編輯推薦】