Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1750
  • Last Modified:

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
0
eljoseph
Asked:
eljoseph
  • 20
  • 13
1 Solution
 
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 20
  • 13
Tackle projects and never again get stuck behind a technical roadblock.
Join Now