vb.net 如何使用单个路径搜索目录和子目录中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22471370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:08:42  来源:igfitidea点击:

How to search for files in directory and subdirectories using a single path

vb.netvisual-studio-2010visual-studio

提问by Jigar patel

I am trying to search for files with extensions ".xml" & ".pdf" in multiple directories under a single path.

我正在尝试在单个路径下的多个目录中搜索扩展名为“ .xml”和“.pdf”的文件。

But here the problem is that the directories consist of many sub directories and i have to read the sub directory which consist of ".xml" & ".pdf" files under a single path And if any one of the files are missing in sub directory the code should be able to get that particular main directory name.

但这里的问题是目录由许多子目录组成,我必须读取由单个路径下的“ .xml”和“.pdf”文件组成的子目录,如果子目录中缺少任何一个文件代码应该能够获得该特定的主目录名称。

Please anyone help me out with this,

请任何人帮我解决这个问题,

Any help will be really appreciated

任何帮助将不胜感激

回答by Fred Kerber

Since the availability of Stacks in VB, I've used them over recursion because of it's simplicity to debug and less chance of a recursive routine getting out of hand.

由于堆栈在 VB 中可用,我已经使用它们而不是递归,因为它易于调试并且递归例程失控的可能性较小。

    Function SearchForFiles(ByVal RootFolder As String, ByVal FileFilter() As String) As List(Of String)
    Dim ReturnedData As New List(Of String)                             'List to hold the search results
    Dim FolderStack As New Stack(Of String)                             'Stack for searching the folders
    FolderStack.Push(RootFolder)                                        'Start at the specified root folder
    Do While FolderStack.Count > 0                                      'While there are things in the stack
        Dim ThisFolder As String = FolderStack.Pop                      'Grab the next folder to process
        Try                                                             'Use a try to catch any errors
            For Each SubFolder In GetDirectories(ThisFolder)            'Loop through each sub folder in this folder
                FolderStack.Push(SubFolder)                             'Add to the stack for further processing
            Next                                                        'Process next sub folder
            For Each FileExt In FileFilter                              'For each File filter specified
                ReturnedData.AddRange(GetFiles(ThisFolder, FileExt))    'Search for and return the matched file names
            Next                                                        'Process next FileFilter
        Catch ex As Exception                                           'For simplicity sake
        End Try                                                         'We'll ignore the errors
    Loop                                                                'Process next folder in the stack
    Return ReturnedData                                                 'Return the list of files that match
End Function

Make sure you include Imports System.Io.Directoryat the top of your source file. Calling is simple:

确保包含Imports System.Io.Directory在源文件的顶部。调用很简单:

Dim Files = SearchForFiles("D:\Programming_VS\", {"*.xml", "*.pdf"})

Which returns a list of strings containing the searched for files.

它返回包含搜索文件的字符串列表。

回答by Codemunkeee

This should at least get you started. It uses recursion to search through files in folders and subfolders.

这至少应该让你开始。它使用递归来搜索文件夹和子文件夹中的文件。

Public Sub rec(ByVal SourcePath As String)
    Dim SourceDir As DirectoryInfo = New DirectoryInfo(SourcePath)
    Dim pathIndex As Integer
    pathIndex = SourcePath.LastIndexOf("\")
    ' the source directory must exist, otherwise throw an exception

    If SourceDir.Exists Then
        Dim SubDir As DirectoryInfo
        For Each SubDir In SourceDir.GetDirectories()
            Console.WriteLine(SubDir.Name)
            rec(SubDir.FullName)
        Next


        For Each childFile As FileInfo In SourceDir.GetFiles("*", SearchOption.AllDirectories).Where(Function(file) file.Extension.ToLower = ".pdf" Or file.Extension.ToLower = ".docx")
            Console.WriteLine(childFile.Name)
        Next
    Else
        Throw New DirectoryNotFoundException("Source directory does not exist: " + SourceDir.FullName)
    End If

End Sub

Sample Usage

示例用法

rec("C:\MyFiles")

回答by NullReferenceException

You can traverse all the files and Sub folders in the Folder.

您可以遍历文件夹中的所有文件和子文件夹。

Const startDir = "c:\"
Set oFSO   = CreateObject("Scripting.FileSystemObject") 
Set oFolder = oFSO.GetFolder(startDir)
Traverse(oFolder)

Sub Traverse(oFldr)
    For Each oSubFolder In oFldr.SubFolders
         TraverseoSubFolder
    Next 

    For Each oFile In oFldr.Files
        //search for the files with extension you required
    Next 
End Sub

回答by kiranmayi ch

Returns the file path for a file by searching all folders and sub folders in a location that is passed as a parameter to the below function

通过在作为参数传递给以下函数的位置中搜索所有文件夹和子文件夹来返回文件的文件路径

        Dim filepath As String = ""
        Dim SourceDir As DirectoryInfo = New DirectoryInfo(AppSettings.Get("mapped_location") + "\AA7BB3B5\TIFF\")
        For Each childFile As FileInfo In SourceDir.GetFiles("*", SearchOption.AllDirectories).Where(Function(file) file.Extension.ToLower = ".tif")
            If childFile.FullName.ToString.Contains(sSelectedfile) Then
                filepath = childFile.FullName
            End If
        Next
        Return filepath
    End Function