ASP.net C# 文件被另一个进程使用

发布于 2024-09-17 01:15:32 字数 2939 浏览 7 评论 0原文

我使用以下页面创建缩略图,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;
        }
    }
}

当我尝试物理或通过代码删除图片文件时,出现“无法访问文件,正在被另一个进程使用”错误。

这是由缩略图缓存引起的吗或者文件是否在我无法发现的地方被关闭?

是否是我的上传文件脚本导致的?

I create thumbnails with the following page, 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;
        }
    }
}

When I try to delete the picture file physically or through code, I get a 'cannot access file, being used by another process" error.

Is this caused by the caching of the thumbnail? Or is the file not being closed somewhere I can't spot?

Could it be my upload file script is causing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

机场等船 2024-09-24 01:15:32

您似乎没有在任何地方关闭 MemoryStream ?仅靠垃圾收集并不能消除文件锁,不是吗?在 ProcessRequest 末尾添加一个 memoryStream.Close() 不会有什么坏处。

You don't appear to be closing your MemoryStream anywhere? Garbage collection alone won't remove a file lock, would it? Tossing in a memoryStream.Close() at the end of ProcessRequest couldn't hurt.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文