Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Every File searcher sample app I find when trying to recurse thru the file system runs into a UnauthorizedAccessException on 1 folder or another.
I have been searching the web for a while and have not come up with a usable solution as most examples for security are for console apps and don't lend well to windows form apps or plain don't work.

I am trying 1 of the VS2008 samples thats called filesystemsample that uses the background worker.

The sample was a download:
downloads\vs 2008 rtm vbsamples\vb 2008 rtm samples\language samples\filesystem\FileSystemSample.sln

There are no imports for anything in this sample.

What I am Wanting to do it to be able to search for a string in a file and return a list of files , which the sample app does till it hits the exception.

So far I have been using a wmi class for searching for files but not contents to get around the exception problem but need something for this particular purpose.

Any help is appreciated
Posted
Updated 24-Jan-17 8:37am
Comments
Sander Rossel 23-Oct-11 13:05pm    
Are you running as an administrator? First thing that comes to mind when talking about security and access priviledges :)
ledtech3 23-Oct-11 19:28pm    
Yes I am ,but all I can do is catch the error.not sure how to do file acess permissions.
Simon_Whale 24-Oct-11 7:08am    
can you post a sample of the code where the error happens?

There are folders and files on the drive that no account has permissions to get into. You're code has to be written to deal with this situation, like wrapping GetFiles and GetDirectories calls in a Try/Catch block. It's really not that difficult.
 
Share this answer
 
Comments
Espen Harlinn 24-Oct-11 10:05am    
Right :)
fjdiewornncalwe 24-Oct-11 10:19am    
Absolutely correct. +5
I think this is what you wanted:

Using this code, I was able to get a list of every file on my c: drive that I have access to, excluding those I don't. No exception was thrown (that wasn't caught, anyway). When you have the list it's simple enough to enumerate them to search for your string.

VB
Private Function GetFilesList(ByVal theFolder As String, Optional ByVal recurseSubdirectories As Boolean = True) As List(Of String)
        Dim filesList As New List(Of String)
        Dim foldersList As New List(Of String)
        Dim tmp As New List(Of String)

        Dim dir As New IO.DirectoryInfo(theFolder)
        If Not dir.Exists Then
            ' Our folder doesn't exist. Handle it here.
            Return Nothing
        End If

        ' Get the files in this folder...
        Try
            filesList.AddRange(Directory.GetFiles(theFolder))
            foldersList.AddRange(Directory.GetDirectories(theFolder))

        Catch ex As Exception
            ' The folder exists, but we don't have access to it.
            Return Nothing
        End Try

        ' Do they only want the files in THIS folder?
        If Not recurseSubdirectories Then
            Return filesList
        Else
            'If there are directories in this folder process them
            For Each folder As String In foldersList
                tmp = GetFilesList(folder)
                If tmp IsNot Nothing Then filesList.AddRange(tmp)
            Next

            Return filesList
        End If

    End Function
 
Share this answer
 
Comments
ledtech3 11-Jun-12 11:06am    
I started Wroking with the Idea Of a List of subfolders catching the Access Denied ones.
But my current version was a not very good.
I'll try your example and let you know.
Thanks for the post
ledtech3 11-Jun-12 15:31pm    
If I use it as is with recurse = True then I get a deadlock condition error if not running inside of a background worker.

Something Interesting I’ve found while testing my code using
System.IO.Directory.GetDirectories(StartDir)
Is that it never Threw a UnauthorizedAccessException
While stepping thru the code to get the list of folders.
pdoxtader 14-Jun-12 8:38am    
Well, how long did you wait? If you're searching your whole hard drive, it may just be taking longer then you would like. The natural solution to that is to begin your string searching right away... for instance, instead of:


filesList.AddRange(Directory.GetFiles(theFolder))


create a new list to contain only the files in that folder, and hand them off to your string search function.

Also, try running this again, and when you seem to have your deadlock, wait a while. Let's see if it's just taking a while to get through your folders.
ledtech3 14-Jun-12 9:37am    
I wasn't using any threading or back ground worker, so after 60 seconds it was saying that it was not responding or in a deadlock condition.I was running this thru the debugger too.And waited several minuets after pressing the continue or ok button and it did not apear to be doing anything looking at it thru Process Explorer. I thought at first it was just because I was trying to return the seach for the files in the start folder and return the found files to the same listbox. but after commenting out the first part it still had the same effect. But If you just get a list of sub folders it is done in a couple of seconds.My test Folder is the C:\Users\David\AppData because I know there are a few folders that will trip the exception.
ledtech3 14-Jun-12 10:46am    
Sorry, had some Coffee now, I redid the sample App and your code works fine by itself. It was my Modified version that was the problem. It is when I try to also return what folders are throwing the exception where I run into a problem,That code is messed up now trying several different things.
What I am trying to do is get the list of files that a string is found in, also get a list that throw the exception so I can go in by hand and verifiy what I am Looking for is not hidden there.
It has a try catch block,
Here is the background worker

VB
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
       Try
           Dim files As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
           ' Look in each file matching the provided wildcards
           If (recurse) Then
               files = My.Computer.FileSystem.FindInFiles(directory, searchText, True, FileIO.SearchOption.SearchAllSubDirectories, wildCards)
           Else
               files = My.Computer.FileSystem.FindInFiles(directory, searchText, True, FileIO.SearchOption.SearchTopLevelOnly, wildCards)
           End If
           For Each foundFile As String In files
               Me.BackgroundWorker1.ReportProgress(0, foundFile)
           Next
       Catch ex As Exception
           MsgBox(ex.Message & vbCrLf & ex.Source, MsgBoxStyle.Information, "Exception Message")
       End Try
   End Sub
 
Share this answer
 
Comments
ledtech3 19-Nov-11 13:49pm    
I Have been Working on this for a while and so far still have not found a way to insert a file permision checking routine into the mix to catch the error and move on so i can keep checking in a recursive search.
Since my first post I have moved the code to its own projet and then had to declair several private vaiables.
1 strange thing did happen after adding the imports for system and system.security ,and then Signed the assembly with a strong name key, it seemed to handle the error more gracefuly.It would just terminate the search as if it didn't find anything, and not throw the error and display the message box(most of the Time).
Go Figure.
But still, it terminated the search.

If recursive = FALSE then it will just check the(loose) files in the folder and return List of files found with the given search string,if any.

If recursive = TRUE then it will get a Access Denied error for the folder where the search begings and terminate the search. In this case the folder and path = C:\ProgramData (Vista 64 bit System)

I need a better understanding how security, and the background worker works.
Most all examples use the console apps, which don't have to deal with windows forms objects.

Any more Ideas ??

Thanks for your time.
ledtech3 25-Nov-11 12:42pm    
After further investigation, it appears the the unauthorized access error stems from the reparse points it hits and not a normal security problem.
I've downloaded and updated the code listed here . http://www.codeproject.com/KB/vista/ReparsePointID.aspx
And am currently trying to see if i can make use of there reparse point dll.
It is written in C and I am a vb guy so it might take a bit to figure out.
Mitchster 24-Jan-17 14:41pm    
In my solutions, I have gotten to this, too. Here is how I am handling it: Once you can identify a Reparse Point (which should be before you run your 'find' code) what I do is just skip the thing. In my case the reparse points are all on the drive, anyways so they will get 'hit' when I get to their actual location. Good luck.
Dave Kreskowiak 24-Jan-17 20:37pm    
You do know this thread is over FIVE YEARS OLD, right? I think the conversation is pretty much dead.
Mitchster 4-Jun-17 10:35am    
But the problem isn't. Do me a favor and get me a list of all the files on your computer modified in the last week, or with the letters 'cat' in the file name. Not a list of ten thousand files and folders that include them but that distinct list... :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900