欢迎来到入门教程网!

vb

当前位置:主页 > 软件编程 > vb >

VB实现的递归复制文件和搜索文件的代码分享

来源:本站原创|时间:2020-01-10|栏目: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是我自己写的一个把路径去掉只剩下文件名和扩展名的方法。

  这两段代码实在是太简单了,所以我觉得没有什么地方要解释了(其实是准备下班走人了)。

上一篇:vbs 定时删除功能实现代码

栏    目:vb

下一篇:使用 iisweb.vbs 列出网站的方法

本文标题:VB实现的递归复制文件和搜索文件的代码分享

本文地址:https://www.xiuzhanwang.com/a1/vb/7261.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有