如何在C#上传后删除文件?

时间:2013-12-03 10:00:47

标签: c# asp.net httphandler

我有一个GenericHandler如下所示只保存jQuery File Upload Plugin中发布的文件,然后对其进行一些处理,然后我想删除主文件,但不能这样做并得到此错误:
The process cannot access the file E:\\Documents\\Visual Studio\\Projects\\NewPreSchoolPanel\\Project\\files\\site\\main-132148717.jpg because it is being used by another process.
这是我的代码:

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

using System;
using System.Web.Script.Serialization;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;

public class bannerUploader : IHttpHandler
{

    GlobalFunctions functions;

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            functions = new GlobalFunctions();

            HttpPostedFile postedFile = context.Request.Files["file"];
            string path = null, name = null, extension = null;

            int width = 0;

            if (HttpContext.Current.Request["width"] != null)
                width = Int32.Parse(HttpContext.Current.Request["width"]);

            path = context.Server.MapPath("~/files/site/");

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            name = DateTime.Now.ToString("HH:mm:ss") + DateTime.Now.Millisecond;
            name = name.Replace(":", "");
            extension = Path.GetExtension(postedFile.FileName);
            while (File.Exists(path + name + extension))
                name += "A";

            postedFile.SaveAs(path + "main-" + name + extension);

            // How can i dispose or close postedFile Here??

            var img = Image.FromFile(context.Server.MapPath("~/files/site/main-" + name + extension));
            object[] resizeResult = null;

            if (width > 800)
                width = 800;
            else if (width > 700)
                width = 700;
            else if (width > 600)
                width = 600;
            else if (300 < width && width < 600)
                width = 300;
            else
                width = 150;

            resizeResult = img.Resize(width, 0);
            ((Image)resizeResult[0]).Save(context.Server.MapPath("~/files/site/resized-" + name + extension));
            ((Image)resizeResult[0]).Dispose();

            context.Response.Write(new
            {
                status = "success",
                main = "~/files/site/main-" + name + extension,
                extension = extension,
                resized = context.Request.Url.GetLeftPart(UriPartial.Authority) + context.Request.ApplicationPath + "/files/site/resized-" + name + extension,
                ratio = resizeResult[1]
            });
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write(new { Result = "FAILED", Message = ex.Message });
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

3 个答案:

答案 0 :(得分:1)

由于您正在上传文件,因此某些进程会使用该文件一段时间。 等待然后删除文件或在global.asax文件中编写代码,该代码将在会话结束后删除文件:

//Code to delete multiple files. It will delete all files created one hour back
    void Session_End(object sender, EventArgs e)
        {
    string[] str = System.IO.Directory.GetFiles("Your file path");
                for (int i = 0; i < str.Length; i++)
                {

                        DateTime dt = System.IO.File.GetCreationTime(str[i]);
                        if (dt < DateTime.Now.AddHours(-1))
                            System.IO.File.Delete(str[i]);

                }
    }

您可以根据需要更改时间,也可以对其进行配置。

答案 1 :(得分:1)

您的问题是FileStream.Close()中基础postedFile.SaveAs()调用与实际删除文件锁之间的最小“滞后”。我打赌安装的防病毒软件会检查并锁定你新创建的文件。 您所要做的就是等待反病毒或文件的任何锁定完成。

以下是一些示例代码:

int tryCounter = 0;
while (true)
{
    try
    {
        tryCounter++;
        //your code here 
        break;
    }
    catch (IOException) //please check if your code does throw an IOException
    {                   //i am just guessing 
        if (tryCounter >= 10)
        {
            throw;
        }

        Thread.Sleep(10);
    }
}

答案 2 :(得分:1)

您没有处置img,因此它仍处于锁定状态(您只是处理已调整大小的图像)。处理完图像后添加以下内容:

img.Dispose();