华南俳烁实业有限公司

考試首頁(yè) | 考試用書 | 培訓(xùn)課程 | 模擬考場(chǎng) | 考試論壇  
  當(dāng)前位置:編程開發(fā) > DotNET > VB.Net > 文章內(nèi)容
  

VB實(shí)現(xiàn)的遞歸復(fù)制文件和搜索文件的代碼分享

 [ 2017年7月5日 ] 【

在程序中要做一個(gè)復(fù)制文件夾的功能,用遞歸寫起來(lái)很方便。后來(lái)要某位仁兄(自己知道就行了 - -)實(shí)現(xiàn)一個(gè)類似的,貌似不是那么順利,這里把復(fù)制文件夾的遞歸代碼丟出來(lái):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Public Shared Sub CopyDirectory(source As String, destination As String)
  If Directory.Exists(destination) = False Then
    Try
      Directory.CreateDirectory(destination)
    Catch ex As Exception
      Logger.LogError(Logger.SourceType.Application, "Copy build process: Cannot create folder: " & destination)
      Return
    End Try
  End If
    
  For Each paths As String In Directory.GetDirectories(source)
    CopyDirectory(paths, Path.Combine(destination, paths.Substring(paths.LastIndexOfAny({""c, "/"c}) + 1)))
  Next
    
  For Each files As String In Directory.GetFiles(source)
    Try
      File.Copy(files, Path.Combine(destination, files.Substring(files.LastIndexOfAny({""c, "/"c}) + 1)), True)
      _copiedFiles += 1
    Catch ex As Exception
      Logger.LogError(Logger.SourceType.Application, "Copy build process: Cannot copy file: " & files)
    End Try
  Next
    
End Sub

遞歸的程序?qū)嵲谑呛芎?jiǎn)潔很漂亮吧?后來(lái)又寫了一個(gè)在文件夾中搜索文件的方法,也是遞歸的,那么在這里就一并丟出來(lái):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
'''
''' Search the specified file in the folder and its sub folders and return its full path name. Empty string if not found.
'''
''' The file to search (no folder).
'''
Public Shared Function SearchFile(folder As String, fileName As String) As String
  If Directory.Exists(folder) = False Then Return String.Empty
    
  fileName = fileName.Trim.ToLower
    
  If fileName.IndexOfAny({""c, "/"c}) >= 0 Then
    fileName = GetFileName(fileName)
  End If
    
  Dim list() As String = Directory.GetFiles(folder)
    
  For i As Integer = 0 To list.GetUpperBound(0)
    If GetFileName(list(i)).Trim.ToLower = fileName Then Return list(i)
  Next
    
  Dim directories() As String = Directory.GetDirectories(folder)
    
  For i As Integer = 0 To directories.GetUpperBound(0)
    Dim return_file As String = SearchFile(directories(i), fileName)
    
    If return_file.Length > 0 Then Return return_file
  Next
    
  Return String.Empty
End Function

  GetFileName是我自己寫的一個(gè)把路徑去掉只剩下文件名和擴(kuò)展名的方法。

 

本文糾錯(cuò)】【告訴好友】【打印此文】【返回頂部
將考試網(wǎng)添加到收藏夾 | 每次上網(wǎng)自動(dòng)訪問考試網(wǎng) | 復(fù)制本頁(yè)地址,傳給QQ/MSN上的好友 | 申請(qǐng)鏈接 | 意見留言 TOP
關(guān)于本站  網(wǎng)站聲明  廣告服務(wù)  聯(lián)系方式  站內(nèi)導(dǎo)航  考試論壇
Copyright © 2007-2013 中華考試網(wǎng)(Examw.com) All Rights Reserved
平昌县| 府谷县| 甘孜县| 黔东| 建始县| 昂仁县| 丰都县| 双桥区| 许昌县| 永嘉县| 洪洞县| 永宁县| 获嘉县| 定兴县| 栾川县| 三门峡市| 汉沽区| 山东省| 广西| 阳城县| 岚皋县| 涿鹿县| 神池县| 荣成市| 黄石市| 麟游县| 红安县| 元阳县| 宜都市| 庆城县| 钦州市| 宜宾县| 大田县| 洪江市| 洪泽县| 石楼县| 灌阳县| 肃北| 磴口县| 丹棱县| 彭山县|