We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

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

eljoseph
eljoseph asked
on
Medium Priority
1,971 Views
Last Modified: 2012-06-22
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
Comment
Watch Question

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?

Author

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

Author

Commented:
The MsgBox displays the following reading

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

The same msg appears 4 all folders

Author

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
Well, that message points you at what I said before:
Directory.Delete only deletes EMPTY folders,
Clear them out with File.Delete first.

Author

Commented:
ok lemme clear the files then
Or you use the single statement :
Directory.Delete ("e:\", true )

:D

Author

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
Does the OS let you delete these files?

Author

Commented:
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)

Author

Commented:
some of the files in my FLASH Drive are read only

Where shall I put File.SetAttributes(sFileName, FileAttributes.Normal) in the code?

Author

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

Author

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

Author

Commented:
PockyMaster where r u? I need ur help
You can set the File.SetAttributes before your File.Delete

Author

Commented:
just post a little sample of code b'coz this is the first time I would b using File.SetAttributes
 For Each sFileName As String In arFiles
            Console.WriteLine(sFileName)
File.SetAttributes(sFileName, FileAttributes.Normal)
            File.Delete(sFileName)

..rest of your code

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
ok I've pasted the File.SetAttributes & am testing it

Author

Commented:
yes thats good it deleted all files..... now the directory.delete can work

Author

Commented:
lemme check the directory.delete

Author

Commented:
files r deleted successfully but the directories r not deleted PockyMaster

Author

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

Author

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

Author

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

Author

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

Author

Commented:
thanx its done finally
:D You're welcome!
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.