tags:

views:

57

answers:

2

Hi, I am using following code to get directory info. it works well if I search topleveldirectory. But when i search alldirectories, it reaches system level information and throws error. Is there any way to avoid searching system level information folder? Thanks

Imports System.IO
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim di As New DirectoryInfo("d:\"), i As Integer
        Dim aryFiles() As FileInfo = di.GetFiles("*.doc", SearchOption.TopDirectoryOnly)
        For i = LBound(aryFiles) To UBound(aryFiles)
            MsgBox(aryFiles(i).FullName)
        Next i
    End Sub
End Class
A: 

Unfortunately not. You will have to work around this by doing your own recursion, where you can add your own exception handlers to ignore those kinds of errors.

ho1
A: 

This code should do the trick for you.

Imports System.IO

Module Module1

    Sub Main()
        Dim folders = New DirectoryInfo("D:\").GetDirectories
        Dim files = New List(Of FileInfo)

        For Each folder In From d In folders Where d.Name <> "System Volume Information"
            files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly))
        Next

        For Each File In files
            MsgBox(File.FullName)
        Next
    End Sub

End Module

I'm assuming your project is .NET 3.5 or higher. Notify me if the assumption is wrong.


Edit
Since you requested for it, I hacked together code to automatically skip inaccessible folders. I did not test the code extensively so I cannot guarantee it will be bug-free.

Imports System.IO

Module Module1

    Sub Main()
        Dim folders = GetAllSubFolders("D:\Alex\Music")
        Dim files = New List(Of FileInfo)

        For Each folder In folders
            files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly))
        Next

        For Each File In files
            Console.WriteLine(File.FullName)
        Next

        Console.ReadLine()
    End Sub

    Function GetAllSubFolders(ByVal path As String) As IEnumerable(Of DirectoryInfo)
        Dim subFolders As New List(Of DirectoryInfo)

        Try
            subFolders.AddRange(New DirectoryInfo(path).GetDirectories())
        Catch ex As Exception
            'error handling code goes here'
        End Try

        Dim innerSubFolders As New List(Of DirectoryInfo)
        For Each folder In subFolders
            innerSubFolders.AddRange(GetAllSubFolders(folder.FullName))
        Next

        'add the inner sub folders'
        subFolders.AddRange(innerSubFolders)

        'return the directories'
        Return subFolders
    End Function

End Module
Alex Essilfie
Your code works ! Thanks but there are lot many folders that have denied to give access. This is impossible to name each and everyone.I need to find some other method.Thanks any way