VB.Net Enumerate files fails with insufficient access

Hi Experts

To get a list of files I am using

Dim files = Directory.EnumerateFiles(Path, "*.*", SearchOption.AllDirectories)

This fails when it hits a folder that if does not have access to.  I can trap the error bit I need to note the folder that failed and continue.
Please can someone advise the correct code to do this?
LVL 2
PNRTAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lokesh B RDeveloperCommented:
Hi,

try this

Dim path As String = ""
Dim filePaths As String() = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)


For Each item As var In filePaths
Next

Open in new window


Note : Make sure you have the permission to read the files from the folder.

https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
0
PNRTAuthor Commented:
Thank you for the reply but I don't think you have read the question.

The code you have mentioned is what I am already using.

I am trying to find a way of continuing after the exception has been raised where permission is not valid
0
Lokesh B RDeveloperCommented:
Hi,

You can check this

Private Sub GetFileList()
	Dim dir As New DirectoryInfo("C:\MyDir")
	Dim file_list As New List(Of String)()
	SearchDirectory(dir, file_list)
End Sub

Private Sub SearchDirectory(dir As DirectoryInfo, files As List(Of String))
	Try
	        For Each file_info As FileInfo In dir.GetFiles("*.*")
			SearchDirectory(subdir, files)
		Next

	Catch
	End Try
	Try
		For Each file_info As FileInfo In dir.GetFiles()
			files.Add(file_info.FullName)
		Next

	Catch
	End Try
End Sub

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

PNRTAuthor Commented:
Thank you for the reply
Am I right that subdir should be dir?  Its not defined anywhere

I get

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
0
Lokesh B RDeveloperCommented:
Hi,

Complete code

Private Sub GetFileList()
	Dim dir As New DirectoryInfo("C:\MyDir")
	Dim files As New List(Of String)()
	SearchDirectory(dir, files)
End Sub

Private Sub SearchDirectory(dir As DirectoryInfo, files As List(Of String))
	Try
		For Each subdir As DirectoryInfo In dir.GetDirectories()
			SearchDirectory(subdir, files)
		Next

	Catch
	End Try
	Try
		For Each file_info As FileInfo In dir.GetFiles("*.*")
			files.Add(file_info.FullName)
		Next

	Catch
	End Try
End Sub

Open in new window

0
SStoryCommented:
This should give you an idea:
Imports System.IO
Imports System.Security

Module Module1

    Sub Main()
        Dim fi As FileInfo = Nothing

        Dim strFile As String
        Try
            For Each strFile In Directory.EnumerateFiles("c:\users\admin", "*.*", SearchOption.AllDirectories)
                Console.WriteLine(strFile)
            Next
        Catch secex As SecurityException
            fi = New FileInfo(strFile)
            Console.Error.WriteLine(String.Format("Security Exception {0}  DirectoryName", secex.Message, fi.DirectoryName))
        Catch unauthex As UnauthorizedAccessException
            fi = New FileInfo(strFile)
            Console.Error.WriteLine(String.Format("Unauthorized Access Exception {0}  DirectoryName:{1}", unauthex.Message, fi.DirectoryName))
        Catch ex As Exception
            MsgBox("ex " & ex.Message)
        End Try
    End Sub

End Module

Open in new window

0
PNRTAuthor Commented:
Thank you Lokesh.  That works fine except that I cant get a list of the folders where it fails

Thank you SStory.  I get the first exception where it fails but then the code stops at that point and doesn't continue.


I was actually hoping for the best of both solutions!! :-)
0
SStoryCommented:
PNRT,

Well, I find the better way to control code like this is to write it yourself and have it search the toplevel only and recursively search other levels.

You should be able to put these two together to make it work.  Modify the code in
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_28685525.html#a40812478

And add in the exceptions and FileInfo variables that I have shown you and do with them whatever you like. It should give you what you are wanting.  Put these exceptions in both try blocks.
0
SStoryCommented:
But just in case....
Imports System.IO
Imports System.Security

Private Sub GetFileList()
	Dim dir As New DirectoryInfo("C:\MyDir")
	Dim files As New List(Of String)()
	Dim FailedFolders As New List(Of String)()
	SearchDirectory(dir, files,FailedFolders)
'upon return, FailedFolders should be populated with issues
        if FailedFolders.Count>0 then
               'do something with them
           for each fld as string in FailedFolders
               'loop through failures
               'do something with each fld string as wanted
            next
        end if
End Sub

Private Sub SearchDirectory(dir As DirectoryInfo, files As List(Of String),FailedFolders as list(of string))
        Dim fi As FileInfo = Nothing

	Try
		For Each subdir As DirectoryInfo In dir.GetDirectories()
			SearchDirectory(subdir, files,FailedFolders)
		Next
        Catch secex As SecurityException
             fi = New FileInfo(strFile)
            Console.Error.WriteLine(String.Format("Security Exception {0}  DirectoryName", secex.Message, fi.DirectoryName))
            FailedFolders.Add(fi.DirectoryName)
        Catch unauthex As UnauthorizedAccessException
            fi = New FileInfo(strFile)
            Console.Error.WriteLine(String.Format("Unauthorized Access Exception {0}  DirectoryName:{1}", unauthex.Message, fi.DirectoryName))
            FailedFolders.Add(fi.DirectoryName)
        Catch ex As Exception
            MsgBox("ex " & ex.Message)
	End Try

	Try
		For Each file_info As FileInfo In dir.GetFiles("*.*")
			files.Add(file_info.FullName)
		Next

	 Catch secex As SecurityException
            Console.Error.WriteLine(String.Format("Security Exception {0}  DirectoryName", secex.Message, file_info.DirectoryName))
            FailedFolders.Add(file_info.DirectoryName)
        Catch unauthex As UnauthorizedAccessException
            Console.Error.WriteLine(String.Format("Unauthorized Access Exception {0}  DirectoryName:{1}", unauthex.Message, file_info.DirectoryName))
            FailedFolders.Add(file_info.DirectoryName)
        Catch ex As Exception
            MsgBox("ex " & ex.Message)
	End Try
End Sub

                                          

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.