罕見VB.NET復制刪除文件完整示例
作者:佚名
文章主要演示了一個關于VB.NET復制刪除文件的一個案例,代碼規(guī)范,其中還有詳細的注釋,這讓有助于大家對代碼理解的正確性。
有些人認為操作文件是一件非常簡單的是,其實并不是,如果你沒有權限你就不能對文件進行更改,但是我們今天不講權限的問題,我們來對VB.NET復制刪除文件這個問題進行簡單的介紹一下。
VB.NET復制刪除文件代碼:
- VB.NET版
- Imports System.IO
- Imports System.IO.Directory
- ' ======================================================
- ' 實現(xiàn)一個靜態(tài)方法將指定文件夾下面的所有內容copy到目標文件夾下面
- ' 如果目標文件夾為只讀屬性就會報錯。
- ' ======================================================
- Public Shared Sub CopyDir(ByVal srcPath As String, ByVal aimPath As String)
- Try
- ' 檢查目標目錄是否以目錄分割字符\結束,如果不是則添加之
- If aimPath(aimPath.Length - 1) <> Path.DirectorySeparatorChar Then
- aimPath += Path.DirectorySeparatorChar
- End If
- '判斷源目錄是否存在,不存在則退出.
- If (Not Directory.Exists(srcPath)) Then Exit Sub
- ' 判斷目標目錄是否存在如果不存在則新建之
- If (Not Directory.Exists(aimPath)) Then Directory.CreateDirectory(aimPath)
- ' 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個數(shù)組
- ' 如果你指向copy目標文件下面的文件而不包含目錄請使用下面的方法
- ' string[] fileList = Directory.GetFiles(srcPath);
- Dim fileList() As String = Directory.GetFileSystemEntries(srcPath)
- ' 遍歷所有的文件和目錄
- For Each FileName As String In fileList
- ' 先當作目錄處理如果存在這個目錄就遞歸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
- ' ======================================================
- ' 實現(xiàn)一個靜態(tài)方法將指定文件夾下面的所有內容Detele
- ' 測試的時候要小心*作,刪除之后無法恢復。
- ' ======================================================
- Public Shared Sub DeleteDir(ByVal aimPath As String)
- Try
- ' 檢查目標目錄是否以目錄分割字符結束如果不是則添加之
- If (aimPath(aimPath.Length - 1) <> Path.DirectorySeparatorChar) Then
- aimPath += Path.DirectorySeparatorChar
- End If
- '判斷待刪除的目錄是否存在,不存在則退出.
- If (Not Directory.Exists(aimPath)) Then Exit Sub
- ' 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個數(shù)組
- ' 如果你指向Delete目標文件下面的文件而不包含目錄請使用下面的方法
- ' string[] fileList = Directory.GetFiles(aimPath);
- Dim fileList() As String = Directory.GetFileSystemEntries(aimPath)
- ' 遍歷所有的文件和目錄
- For Each FileName As String In fileList
- If (Directory.Exists(FileName)) Then
- ' 先當作目錄處理如果存在這個目錄就遞歸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
以上就是關于VB.NET復制刪除文件的一個代碼的演示,跑跑試試吧!
【編輯推薦】
責任編輯:田樹
來源:
博客