程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> Visual Basic語言 >> VB.NET >> VB完成的遞歸復制文件和搜刮文件的代碼分享

VB完成的遞歸復制文件和搜刮文件的代碼分享

編輯:VB.NET

VB完成的遞歸復制文件和搜刮文件的代碼分享。本站提示廣大學習愛好者:(VB完成的遞歸復制文件和搜刮文件的代碼分享)文章只能為提供參考,不一定能成為您想要的結果。以下是VB完成的遞歸復制文件和搜刮文件的代碼分享正文


在法式中要做一個復制文件夾的功效,用遞歸寫起來很便利。後來要某位仁兄(本身曉得就好了 - -)完成一個相似的,貌似不是那末順遂,這裡把復制文件夾的遞歸代碼丟出來:

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

遞歸的法式其實是很簡練很英俊吧?後來又寫了一個在文件夾中搜刮文件的辦法,也是遞歸的,那末在這裡就一並丟出來:

''' <summary>
''' Search the specified file in the folder and its sub folders and return its full path name. Empty string if not found.
''' </summary>
''' <param name="fileName">The file to search (no folder).</param>
''' <remarks></remarks>
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是我本身寫的一個把途徑去失落只剩下文件名和擴大名的辦法。

  這兩段代碼其實是太簡略了,所以我認為沒有甚麼處所要說明了(實際上是預備上班走人了)。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved