[英]c# - Returning a JPEG in web api, cant delete file because it is being used by another process
I am trying to retrieve a image from the file system and pass it's content through a HttpResponseMessage and then delete the image after. 我正在尝试从文件系统中检索图像,并将其内容通过HttpResponseMessage传递,然后将其删除。 I can get the response to pass the image succesfully but cannot delete it because of the error:
我可以获取成功通过图像的响应,但是由于错误而无法删除它:
The process cannot access the file 'C:...\\Temp\\c8530aae-ae92-49f3-8f62-cd1f5467fe8a1.jpeg' because it is being used by another process.
该进程无法访问文件'C:... \\ Temp \\ c8530aae-ae92-49f3-8f62-cd1f5467fe8a1.jpeg',因为该文件正在被另一个进程使用。
My controller code: 我的控制器代码:
{
Image returnImg = Image.FromFile(@"C:\...\Temp\" + id + "1" + ".jpeg");
MemoryStream memoryStream = new MemoryStream();
returnImg.Save(memoryStream, ImageFormat.Jpeg);
var message = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
message.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
File.Delete(@"C:\...\Temp\" + id + "1" + ".jpeg"); //error is on this line execution
return message
}
I figure it has something to do with the memory stream, is there a close operation I am missing? 我认为这与内存流有关,我是否缺少关闭操作?
The Image object returnImg implements the IDisposable interface. Image对象returnImg实现IDisposable接口。 You will have to place it in a using {} block.
您将必须将其放置在using {}块中。 Also, MemoryStream is not closed properly.
另外,MemoryStream没有正确关闭。
When a class implements IDisposable class and you are creating an instance of the class you are supposed to wrap it in a using block, so the class can destroy the object properly.Try: 当一个类实现IDisposable类并且正在创建该类的实例时,应该将其包装在using块中,以便该类可以正确地销毁对象。
{
using(Image returnImg = Image.FromFile(@"C:\...\Temp\" + id + "1" + ".jpeg"))
{
using(MemoryStream memoryStream = new MemoryStream())
{
returnImg.Save(memoryStream, ImageFormat.Jpeg);
var message = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
}
message.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
}
File.Delete(@"C:\...\Temp\" + id + "1" + ".jpeg"); //error is on this line execution
return message
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.