Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
VB
<pre> Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)


What I have tried:

Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)
Posted
Updated 30-May-18 21:35pm

There are probably several problems here: the one you have noticed, and the one you haven't, not yet...

Without your code we can;t tell, but the chances are that you are loading the image using Image.FromFile Method (String) (System.Drawing)[^] or one of it's overloads - and the documentation clearly states:
Quote:
The file remains locked until the Image is disposed.
Which means that while the Image instance exists in your app, teh soure fiule of the image is in use, it cannot be opened for writing, or deleted.

The way round this is to use Image.FromFile to load the image, copy it, then Dispose the original:
Public Function GetImage(ByVal path As String) As Image
    Using im As Image = Image.FromFile(path)
        Return New Bitmap(im)
    End Using
End Function
The original file is then no longer locked and can be overwritten or deleted.

But that's just the problem you have noticed - there is a bigger one looming on the horizon. Your app will fail in production, because you are using the EXE file folder to store data - and in production, that will be under the "Program Files" folder, which is not writable without admin permissions. See here: Where should I store my data?[^] - the code is in C#, but it's trivial to convert to VB.
 
Share this answer
 
Comments
Richard Deeming 31-May-18 12:34pm    
Those remarks are new - I'm sure it used to keep the file locked until the AppDomain was unloaded. Perhaps they've finally fixed the problem?
OriginalGriff 31-May-18 12:47pm    
Not from what I remember - it's been like that since at least .NET V2.0 that I can remember.
Richard Deeming 31-May-18 12:56pm    
That's odd. Must be my brain getting old then. :)
Embed your code in a try catch handler, catch exceptions, and report errors using the message text of the execption:
VB
Try
    Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)
Catch e As Exception
    MessageBox.Show(e.ToString)
End Try
In your case it might be an access denied error when your application is located in a system folder like Program Files (user accounts have no write and delete permission on such folders), a file not found error, or that the file is locked. But only the error message will tell you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900