C# 该进程无法访问该文件,因为另一个进程asp.net正在使用该文件
我有以下方法可以调整给定图像的大小并缓存它C# 该进程无法访问该文件,因为另一个进程asp.net正在使用该文件,c#,asp.net,asp.net-mvc,caching,system.io.file,C#,Asp.net,Asp.net Mvc,Caching,System.io.file,我有以下方法可以调整给定图像的大小并缓存它 [OutputCache(Duration = 3600, VaryByParam = "id")] public ActionResult UserFace(int id) { var cacheKey = String.Format("userPhotoURICacheKey_{0}", id); var defaultFileCacheKey = String.Format("userPhotoD
[OutputCache(Duration = 3600, VaryByParam = "id")]
public ActionResult UserFace(int id)
{
var cacheKey = String.Format("userPhotoURICacheKey_{0}", id);
var defaultFileCacheKey = String.Format("userPhotoDefaultCacheKey");
HttpContext.Cache[cacheKey] = HttpContext.Cache[cacheKey] ?? UserService.GetPhotoURI(id) ?? string.Empty;
var userPhoto = (String)HttpContext.Cache[cacheKey];
if (!string.IsNullOrEmpty(userPhoto))
{
var filename = id + ".jpg";
//crop and resize
var image = Image.FromFile(new Uri(userPhoto).LocalPath);
const int resW = 200;
const int resH = 200;
var minEdge = Math.Min(image.Width, image.Height);
var scaleFactor =(float) minEdge/Math.Min(resH, resW);
var newImage = new Bitmap(resW, resH);
var sufrace = Graphics.FromImage(newImage);
sufrace.InterpolationMode = InterpolationMode.HighQualityBicubic;
sufrace.DrawImage(image, 0, 0, image.Width / scaleFactor, image.Height / scaleFactor);
var stream = new MemoryStream();
newImage.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var file = File(stream, "image/jpg", filename);
return file;
}
HttpContext.Cache[defaultFileCacheKey] = HttpContext.Cache[defaultFileCacheKey] ?? File("~/Content/images/no_photo.jpg", "image/jpg", "nophoto.jpg");
return (FileResult)HttpContext.Cache[defaultFileCacheKey];
}
在另一种方法中,我尝试用新的图像更新缓存的图像
public void UploadUserImage(byte[] arr, int userId)
{
Stream stream = new MemoryStream();
stream.Write(arr, 0, arr.Length);
using (var dataManager = factory.GetDataManager())
{
var userRepository = dataManager.GetRepository<IUserRepository>();
var user = GetByID(userId);
user.PhotoURI =
storageFactory.CreateFileStorageSender()
.Send(storageConfig.UsersPhotoPath, user.Id.ToString(), stream);
user.PhotoSize = stream.Length;
userRepository.Save(user);
dataManager.Commit();
}
}
public void UploadUserImage(字节[]arr,int userId)
{
Stream=新的MemoryStream();
流写入(arr,0,arr.Length);
使用(var dataManager=factory.GetDataManager())
{
var userRepository=dataManager.GetRepository();
var user=GetByID(userId);
user.PhotoURI=
storageFactory.CreateFileStorageSender()文件
.Send(storageConfig.UsersPhotoPath,user.Id.ToString(),stream);
user.PhotoSize=stream.Length;
userRepository.Save(用户);
Commit();
}
}
我收到“进程无法访问该文件,因为它正被另一个进程使用”错误。请在完成“调整大小”后处理图像以再次使用它。您需要从代码中处理“文件”、“图像”和“新图像”对象。我认为文件对象的句柄给了您这个错误。尝试搜索。处理图像。
UserFace
中的图像
,以及UploadUserImage
中的流
,都需要使用块。UserFace
中的MemoryStream
不应继续位于using
块中,因为它成为FileStreamResult
调用创建的FileStreamResult
的一部分。执行结果时,ASP.NET MVC将调用FileStreamResult
上的Dispose
。。