[英]The process cannot access the file because it is being used by another process asp.net c#?
I am trying to delete an image from a junk folder after uploading and resizing the image to my server folder. 我上传并调整图像大小到我的服务器文件夹后,我试图从垃圾文件夹中删除图像。 But then I am receiving this message which is not letting me delete the image from the junk folder.
但后来我收到这条消息,不让我从垃圾文件夹中删除图像。 How do I resolve this issue?
我该如何解决这个问题?
if (FileUpload1.HasFile)
{
long fileSize = FileUpload1.FileContent.Length;
double sizeinBytes = fileSize * 0.001;
FileUpload1.SaveAs(Server.MapPath("~/junk/" + FileUpload1.FileName));
string filepath = Server.MapPath("~/junk/" +FileUpload1.FileName);
System.IO.FileStream fs = System.IO.File.OpenRead(filepath);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
Bitmap resizedimage = ResizeImage(image, 500, 500);
resizedimage.Save(Server.MapPath("~/images/" + FileUpload1.FileName + ".jpeg"));
Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
var filePath = Server.MapPath("~/junk/" + FileUpload1.FileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
You have to encapsulate your Filestream like below, so that it gets disposed when finished: 您必须像下面一样封装您的文件流,以便在完成时将其处理:
using(FileStream fs = System.IO.File.OpenRead(filepath))
{
//do stuff
}
//delete
if (FileUpload1.HasFile)
{
long fileSize = FileUpload1.FileContent.Length;
double sizeinBytes = fileSize * 0.001;
FileUpload1.SaveAs(Server.MapPath("~/junk/" + FileUpload1.FileName));
string filepath = Server.MapPath("~/junk/" + FileUpload1.FileName);
using (System.IO.FileStream fs = System.IO.File.OpenRead(filepath))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
Bitmap resizedimage = ResizeImage(image, 500, 500);
resizedimage.Save(Server.MapPath("~/images/" + FileUpload1.FileName + ".jpeg"));
}
Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
var filePath = Server.MapPath("~/junk/" + FileUpload1.FileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.