在程序中要做一個(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ò)展名的方法。
全國(guó)職稱計(jì)算機(jī)考試速成過(guò)關(guān)系列套裝:W .. 定價(jià):¥133 優(yōu)惠價(jià):¥133.0 更多書籍 | |
全國(guó)職稱計(jì)算機(jī)考試速成過(guò)關(guān)系列套裝:W .. 定價(jià):¥124 優(yōu)惠價(jià):¥124.0 更多書籍 |