Link to home
Start Free TrialLog in
Avatar of eljoseph
eljoseph

asked on

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
Avatar of PockyMaster
PockyMaster
Flag of Netherlands image

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?
Avatar of eljoseph
eljoseph

ASKER

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?
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
The MsgBox displays the following reading

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

The same msg appears 4 all folders
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
Well, that message points you at what I said before:
Directory.Delete only deletes EMPTY folders,
Clear them out with File.Delete first.
ok lemme clear the files then
Or you use the single statement :
Directory.Delete ("e:\", true )

:D
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
Does the OS let you delete these files?
Yes if I delete these folders manually from my FLASH DRIVE, they delete successfully

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

Where shall I put File.SetAttributes(sFileName, FileAttributes.Normal) in the code?
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
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
PockyMaster where r u? I need ur help
You can set the File.SetAttributes before your File.Delete
just post a little sample of code b'coz this is the first time I would b using File.SetAttributes
ASKER CERTIFIED SOLUTION
Avatar of PockyMaster
PockyMaster
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok I've pasted the File.SetAttributes & am testing it
yes thats good it deleted all files..... now the directory.delete can work
lemme check the directory.delete
files r deleted successfully but the directories r not deleted PockyMaster
ok just post ur comments & I'll stay in-touch with u after 2 hours
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
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
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

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
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

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
thanx its done finally
:D You're welcome!