Файл ASP.net С# используется другим процессом

Я создаю эскизы со следующей страницей Thumbnail.ashx:

<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class Thumbnail : IHttpHandler {

    private int _thumbnailSize = 150;

    public void ProcessRequest(HttpContext context) {
        string photoName = context.Request.QueryString["p"];

        string cachePath = Path.Combine(HttpRuntime.CodegenDir, photoName + ".png");
        if (File.Exists(cachePath)) {
            OutputCacheResponse(context, File.GetLastWriteTime(cachePath));
            context.Response.WriteFile(cachePath);
            return;
        }
        string photoPath = context.Server.MapPath("../uploads/originals/" + photoName);
        Bitmap photo;
        try {
            photo = new Bitmap(photoPath);
        }
        catch (ArgumentException) {
            throw new HttpException(404, "Photo not found.");
        }
        context.Response.ContentType = "image/png";
        int width, height;
        if (photo.Width > photo.Height) {
            width = _thumbnailSize;
            height = photo.Height * _thumbnailSize / photo.Width;
        }
        else {
            width = photo.Width * _thumbnailSize / photo.Height;
            height = _thumbnailSize;
        }
        Bitmap target = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(target)) {
            graphics.CompositingQuality = CompositingQuality.HighSpeed;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.DrawImage(photo, 0, 0, width, height);
            using (MemoryStream memoryStream = new MemoryStream()) {
                target.Save(memoryStream, ImageFormat.Png);
                OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew)) {
                    memoryStream.WriteTo(diskCacheStream);
                }
                memoryStream.WriteTo(context.Response.OutputStream);
            }
        }
    }

    private static void OutputCacheResponse(HttpContext context, DateTime lastModified) {
        HttpCachePolicy cachePolicy = context.Response.Cache;
        cachePolicy.SetCacheability(HttpCacheability.Public);
        cachePolicy.VaryByParams["p"] = true;
        cachePolicy.SetOmitVaryStar(true);
        cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
        cachePolicy.SetValidUntilExpires(true);
        cachePolicy.SetLastModified(lastModified);
    }

    public bool IsReusable {
        get {
            return true;
        }
    }
}

Когда я пытаюсь удалить файл изображения физически или с помощью кода, я получаю сообщение об ошибке «Не удается получить доступ к файлу, который используется другим процессом».

Это вызвано кешированием эскиза? Или файл не закрывается где-то, чего я не могу заметить?

Может ли это быть вызвано моим сценарием загрузки файла?


person Tom Gullen    schedule 02.09.2010    source источник


Ответы (1)


Кажется, вы нигде не закрываете свой MemoryStream? Сама по себе сборка мусора не снимет блокировку файла, не так ли? Добавление memoryStream.Close() в конце ProcessRequest не повредит.

person James    schedule 09.09.2010