删除图片框使用的图像时出现问题 [英] Problem deleting an image used by a picturebox

查看:73
本文介绍了删除图片框使用的图像时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre> Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)





我尝试了什么: < br $>




What I have tried:

Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)

推荐答案

这里可能存在几个问题:你注意到的问题,还有你没注意到的问题,还没有......


如果没有您的代码,我们可以告诉您,但您可能正在使用 Image.FromFile Method(String)(System.Drawing) [ ^ ]或其中一个重载 - 文档明确指出:
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:
引用:

fil e保持锁定,直到图像处理完毕。

The file remains locked until the Image is disposed.

这意味着当您的应用程序中存在Image实例时,图像的图像正在使用中,无法打开或删除。



这种方法是使用Image.FromFile加载图像,复制它,然后处理原始图像:

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

原始文件不再被锁定,可以被覆盖或删除。



但这只是你注意到的问题 - 有一个更大的问题迫在眉睫地平线。您的应用程序将在生产中失败,因为您正在使用EXE文件文件夹来存储数据 - 并且在生产中,这将位于Program Files文件夹下,该文件夹在没有管理员权限的情况下是不可写的。请参阅此处:我应该在哪里存储数据? [ ^ ] - 代码是在C#中,但转换为VB很简单。

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.


使用execption的消息文本将代码嵌入try catch处理程序,捕获异常并报告错误:

Embed your code in a try catch handler, catch exceptions, and report errors using the message text of the execption:
Try
    Directory.Delete(Application.StartupPath & "\test\ax1.jpg", True)
Catch e As Exception
    MessageBox.Show(e.ToString)
End Try

在您的情况下,当您的应用程序被定位时,它可能是拒绝访问错误在 Program Files 等系统文件夹中(用户帐户对此类文件夹没有写入和删除权限),找不到文件错误或文件被锁定。但只有错误信息会告诉你。

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.


这篇关于删除图片框使用的图像时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆