该进程无法访问该文件,因为它正由另一个进程asp.net使用

时间:2015-06-09 10:01:56

标签: c# asp.net asp.net-mvc caching system.io.file

我有以下方法调整给定图像的大小并缓存它

ISODate

在另一种方法中,我尝试使用新的

更新缓存的图像
[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];
    }  

我得到"进程无法访问该文件,因为它正被另一个进程使用"错误。

2 个答案:

答案 0 :(得分:2)

完成调整后再处理图像以再次使用它。

答案 1 :(得分:0)

你需要处理"文件","图像"和" newImage"代码中的对象。我认为文件对象的句柄给你这个错误。