tags:

views:

48

answers:

2

In my app i have to copy and then delete image files from memory cards, the problem comes when some of the card inadvertantly have the "Lock" switch engaged turning them to read only.

When trying to delete these files i want to log the failure to delete but not show any UI messages until a time of my choosing.

Here is some sample code i am having trouble with.

Sub Main()
    Try
        System.IO.File.Delete("K:\BYZTCSQ_0050.JPG")
    Catch ex As Exception
        'Error would be logged here
    End Try
End Sub

This works fine when debuging i.e. it tries to delete the file and if not the error is caught and i can proccess it as nessecary, but when i build and run the app i get an error message telling me that the file cannot be deleted.

To test this code you will need a drive that can be physically set to read only (USB memory key, SD card) and try to delete a file on it while debuging and after a build.

Why would the same code run differently and how can i stop the excess error messages?

A: 

Instead of wrapping it in a try/catch block, test to see if the file exists before trying to execute the delete:

Dim strFilePath as String = "K:\BYZTCSQ_0050.JPG"
If File.Exists(strFilePath) Then
   System.IO.File.Delete(strFilePath)
End If
ianpoley
That's not the problem he is having. The lock switch makes the media readonly.
Matthew Whited
This is purely test code and i am making an explicit reference to a file i KNOW exists.
Lloyd Quenby
The file exists - he's having problems deleting it from the media
rwmnau
+1  A: 

You can try to create a file on the memory card. For reasons only known to Microsoft (or not), creating a file on a copy-protected drive will raise the error condition in the Try block while deleting a file will not. Incidentally, I got the same odd result -- catching the delete worked fine in debug mode, but not from the .exe.

Imports System.IO
...
Try
  fs = File.Create(drive & "\tmp.~tmp")
Catch ex As Exception
  copyprotected = true
End Try

if not copyprotected then 
  file.delete(drive & "\tmp.~tmp")
  file.delete(the file you wanted to in the first place)
end if
xpda
So simple, just how i like it thanks
Lloyd Quenby
This behavior doesn't seem right - is there a connect bug filed for it?
rwmnau