2
I have an image that is my user’s avatar, then I need to delete and I have the following code snippets:
Action that is used in file import
public void MinhaActionParaImport()
{
var arquivo = Request.Files[0];
var caminho = Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg");
arquivo.SaveAs(caminho);
}
Method used to remove the image
public void DeletarImagem()
{
var imagem = Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg");
if (System.IO.File.Exists(imagem))
System.IO.File.Delete(imagem);
}
Method used to display the image
public ActionResult ExibirImagem()
{
Image image = Image.FromFile(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"));
ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == image.RawFormat.Guid);
return File(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"), codec.MimeType);
}
View
<img src="@Url.Action("ExibirImagem")"/>
When trying to do this, I get the following error:
The process cannot access the file because it is being used by Another process
What can I do to force the deletion of this image?
Usually it is the
.vshost
that holds the file pointers. How did you upload the file?– Leonel Sanches da Silva
@Gypsy Heart Mendez, I used the
SaveAs()
ofHttpPostedFileBase
.– Filipe Oliveira
Can you put the full code in the question, please?
– Leonel Sanches da Silva
I made the changes.
– Filipe Oliveira
The message indicates that this file is open in some other application. It may be in your ASP.NET MVC application or outside it. Your code is ok.
– Leonel Sanches da Silva
It’s probably in my MVC application. If it’s being displayed on the page during deletion, can’t the operation be done? Is there any way to force this?
– Filipe Oliveira
You open the image before then? If yes, you can again edit your question and put the code?
– Leonel Sanches da Silva
Add all relevant code to image manipulation.
– Marcus Vinicius
I added the code and saw the problem, I was opening one
Image
without theusing
. If you want to come up with a legal answer, feel free. If you don’t, I’ll do it later.– Filipe Oliveira
@Filipeoliveira No need. Your answer is great. + 1.
– Leonel Sanches da Silva