并在C#中删除图像

并在C#中删除图像

本文介绍了覆盖文件(图像),并在C#中删除图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,用户可以使用它来上传图片。它有一个预览按钮,所以当用户选择一个图像,并点击预览,发生回发,我将图像保存到临时文件夹,调整大小,并显示在页面上。从那里,用户可以是提交表格编辑表格。如果他提交,一切都还好,我把调整大小的图像复制到正确的文件夹中。



如果他点击编辑并选择另一个图像,我需要删除上传的文件如果我这样做:

  File.Delete(HostingEnvironment.MapPath(TmpDirectory + PostImageName +.jpg )); 
File.Delete(HostingEnvironment.MapPath(TmpDirectory + PostImageName +_small_.jpg));

我得到一个异常说,其他进程正在使用图像,它不能删除。 (甚至在回发之后!)

另外,如果不是删除那个文件,我试图用相同的名字保存新的图像,以便覆盖它,仍然抛出的错误,因为文件已经存在。

用户可以编辑/预览的次数没有限制,所以我不能保存文件递增(它不甚至有道理这样做)

另外,回发后,当用户回到编辑模式并查看表单时,文件上传控件是空的。我怎样才能让文件上传控制保留的价值?所有其他文本框和文本区域和复选框的行为正常。

总结这些是我的问题:

1 )如何在地球上(或者说,在C#中)我可以删除文件,而不会得到这种异常?



1)如何覆盖文件?
2)如何使文件上传控件在回发之间保留它的值。

谢谢。

I have a simple form which the users can use to upload images. It has a preview button so when User selects an image and clicks on preview, a postback occurs and I save the image to temporary folder and resize it and show it on the page. from there, the user can either submit form or edit the form. If he submits, everything is okay, I copy the resized image into correct folder.

If he clicks edit, and chooses another image, I need to delete the uploaded files (both original and resized) and If I do this:

File.Delete(HostingEnvironment.MapPath(TmpDirectory + PostImageName + ".jpg"));
File.Delete(HostingEnvironment.MapPath(TmpDirectory + PostImageName + "_small_.jpg"));

I get an exception saying some other process is using the image and It cant delete. (even after postback!)

and Also, if, instead of deleting that file, I try to save the new image with the same name so that it would overwrite, it still throws the error because file already exists.

There is no limit to the number of times the user can edit / preview so I cant save files incrementally (it doesn't even make sense to do this)

Also, after the postback, when the user goes back to edit mode and views the form the file upload control is empty. how can I get the file upload control to retain the value? all the other textboxes and text areas and checkboxes behave properly.

to summarize these are my questions:

1) how on earth (or rather, in c#) can I delete files without getting that exception?
OR
1) how to overwrite files?
2) how to make the file upload control retain its value between postbacks.

Thanks.

解决方案

The exception talks for itself : Your file is still being used/opened by another process, i.e. thread, that you have launched. I bet it is the process by which you open the image file for reading. Make sure you have closed the relevant stream, ten bucks that it will solve your issue.

这篇关于覆盖文件(图像),并在C#中删除图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 11:55