How to handle "System.UnauthorizedAccessException/System.IO.IOException" errors?

I've a code that deletes all the folders. I was just testing it for my FLASH DRIVE but on runtime gave me some "System.IO.IOException" error. Even if I try to delete only files, not folders, some "System.UnauthorizedAccessException" error appears. Why is it so?

The code is as follows;

    Sub Main()
        Dim arFiles As ArrayList = GetAllFiles("E:\")

        For Each sFileName As String In arFiles
            Console.WriteLine(sFileName)
            Directory.Delete(sFileName)
        Next
    End Sub

    Public Function GetAllFiles(ByVal basePath As String) As ArrayList

        Dim arFiles As New ArrayList

        Try
            For Each folder As String In Directory.GetDirectories(basePath)
                arFiles.Add(folder)
            Next

            '            For Each filename As String In Directory.GetFiles(basePath)
            '           arFiles.Add(filename)
            '          Next
        Catch ex As Exception
        End Try

        Return arFiles
    End Function
eljosephAsked:
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.

PockyMasterCommented:
For Each sFileName As String In arFiles
            Console.WriteLine(sFileName)
try
            Directory.Delete(sFileName)
catch ex as exception
messagebox.show (string.format("Exception {0} occurred for file {1}", ex.Message, sFileName))

end try

        Next

You will see which file you couldn't delete... maybe it helps?
0
eljosephAuthor Commented:
Dear PockyMaster,

   The flash drive contains abt 9 folders & the MSgBox appears for each. It mean no folder has been deleted.

    What 2 do then?
0
PockyMasterCommented:
If you delete using Directory.Delete your folders should be empty first

Directory.Delete deletes folders, not files.

Files can be deleted with
File.Delete
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

eljosephAuthor Commented:
The MsgBox displays the following reading

"Exception The directory is not empty, occurred for E:\CruzerLock2"

The same msg appears 4 all folders
0
eljosephAuthor Commented:
Yes u r right, ok then lemme know the change in above code. I'll try it here.

Plz post the above code with the modifications
0
PockyMasterCommented:
Well, that message points you at what I said before:
Directory.Delete only deletes EMPTY folders,
Clear them out with File.Delete first.
0
eljosephAuthor Commented:
ok lemme clear the files then
0
PockyMasterCommented:
Or you use the single statement :
Directory.Delete ("e:\", true )

:D
0
eljosephAuthor Commented:
I tried to clear all files at first using File.Delete command but it deleted files from only 2 folders n gave the following error msg at a particular folder

"An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorib.dll

Additional Info: Access to the path 'e:/PocketCache Trial Version/HelpFiles/CruzerPocketCache.chm' is denied"

Even when I tried Directory.Delete ("e:\", true ), the same above error appeared but the ExceptionType was 'ArgumentException'

The code I modified is as below

    Sub Main()
        Dim arFiles As ArrayList = GetAllFiles("E:\")

        For Each sFileName As String In arFiles
            Console.WriteLine(sFileName)
            File.Delete(sFileName)
            '            Try
            '           Directory.Delete(sFileName)
            '          Catch ex As Exception
            '         MessageBox.Show(String.Format("Exception {0} occurred for file {1}", ex.Message, sFileName))
            '        End Try
        Next
    End Sub

    Public Function GetAllFiles(ByVal basePath As String) As ArrayList

        Dim arFiles As New ArrayList

        Try
            For Each folder As String In Directory.GetDirectories(basePath)
                arFiles.AddRange(GetAllFiles(folder))
            Next

            For Each filename As String In Directory.GetFiles(basePath)
                arFiles.Add(filename)
            Next
        Catch ex As Exception
        End Try

        Return arFiles
    End Function

Plz lemme know 4 further changes
0
PockyMasterCommented:
Does the OS let you delete these files?
0
eljosephAuthor Commented:
Yes if I delete these folders manually from my FLASH DRIVE, they delete successfully

or u mean something else?
0
PockyMasterCommented:
Are the files readonly perhaps?
0
PockyMasterCommented:
if that is the case, try something like
 File.SetAttributes(sFileName, FileAttributes.Normal)
0
eljosephAuthor Commented:
some of the files in my FLASH Drive are read only

Where shall I put File.SetAttributes(sFileName, FileAttributes.Normal) in the code?
0
eljosephAuthor Commented:
Yes there r some of the read-only files existing in my FLASH drive, morover plz reply me back how 2 use the File.SetAttribute in my code

I'm waiting 4 ur reply
0
eljosephAuthor Commented:
Yes there r some of the read-only files existing in my FLASH drive, morover plz reply me back how 2 use the File.SetAttribute in my code

I'm waiting 4 ur reply
0
eljosephAuthor Commented:
PockyMaster where r u? I need ur help
0
PockyMasterCommented:
You can set the File.SetAttributes before your File.Delete
0
eljosephAuthor Commented:
just post a little sample of code b'coz this is the first time I would b using File.SetAttributes
0
PockyMasterCommented:
 For Each sFileName As String In arFiles
            Console.WriteLine(sFileName)
File.SetAttributes(sFileName, FileAttributes.Normal)
            File.Delete(sFileName)

..rest of your code
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
eljosephAuthor Commented:
ok I've pasted the File.SetAttributes & am testing it
0
eljosephAuthor Commented:
yes thats good it deleted all files..... now the directory.delete can work
0
eljosephAuthor Commented:
lemme check the directory.delete
0
eljosephAuthor Commented:
files r deleted successfully but the directories r not deleted PockyMaster
0
eljosephAuthor Commented:
ok just post ur comments & I'll stay in-touch with u after 2 hours
0
PockyMasterCommented:
Yeah, because you removed files only now...
And probably you cannot do Directory.Delete because it's a root folder.

What you might do, is get all the folders you have in e:\

and do a Directory.Delete on them
e.g.

Directory.Delete(sFolderName, true)
 
Actually it seems like a lot of work for something so simple :D

      For Each sEmptyFolder As String In Directory.GetDirectories("E:\")
            Directory.Delete(sEmptyFolder, True)
        Next
0
eljosephAuthor Commented:
Congratulations !!!! u did what other experts can't do since the last week

All points 2 u PockyMaster...... u r truly a genius.......

Just tell me if suppose I set some folder on SHARING & I'm deleting it using ur idea, will it even work then. I hope it will. Plz do reply back 4 this last answer
0
eljosephAuthor Commented:
PockyMaster is it possible if u could 1 more change within the code.

Suppose a file is being used, then ofcourse the DELETE program will stop functioning. Is it possible that if the file is being used by another process, the program must skip that file & continue deleting others?

Do reply 4 that

0
eljosephAuthor Commented:
If any file is being processed while the program is running, the System.IO.IOException error is generated. Therefore, its better the program must skip that process & continue deleting others
0
PockyMasterCommented:
Yeah, you can add a try catch around your Delete Statement

e.g.

psuedo code

Try
   File.Delete (...)
Catch Ex as Exception
  Console.WriteLine (String.Format("Could not delete {0}", sFileName))
End try

0
PockyMasterCommented:
Maybe off topic, but some people will not answer if you hand out just 20 points.. If you need more attention, try to raise it a bit  :D
0
eljosephAuthor Commented:
thanx its done finally
0
PockyMasterCommented:
:D You're welcome!
0
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.