开发者

How to cancel and delete the uploading file in asp.net mvc 3?

开发者 https://www.devze.com 2023-04-12 19:55 出处:网络
I am using a filestream to receive a large file in my controller. codes below: [HttpPost] public JsonResult Create(string qqfile, Attachment attachment)

I am using a filestream to receive a large file in my controller. codes below:

[HttpPost]
public JsonResult Create(string qqfile, Attachment attachment)
{
    Stream inputStream = HttpContext.Request.InputStream;
    string fullName = ingestPath + Path.GetFileName(qqfile);


    using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
    {
        try
        {
            var buffer = new byte[1024];

            int l = inputStream.Read(开发者_如何学编程buffer, 0, 1024);
            while (l > 0)
            {
                fs.Write(buffer, 0, l);
                l = inputStream.Read(buffer, 0, 1024);
            }
            return Json(new {success = "true"});
        }
        catch (Exception)
        {
            return Json(new {success = "false"});
        }
        finally
        {
            inputStream.Flush();
            inputStream.Close();

            fs.Flush();
            fs.Close();
        }
    }
}

And in my page ajax method, I add a button to cancel the file uploading and delete the unfinished file from disk. The ajax request to the action named "Cancel":

        [HttpPost]
    public JsonResult Cancel(string filename)
    {
        string localName = HttpUtility.UrlDecode(filename);
        string fullName = ingestPath + Path.GetFileName(localName);
        if (System.IO.File.Exists(fullName))
        {
            System.IO.File.Delete(fullName);
        }
        return Json(new {cancle = true});
    }

The problem is: the file can not delete, and the exception message is

the process cannot access the file 'e:\tempdata\filename_xxx.xxx'because it is being used by another process.

I think it is because that ,the filestream of this file is not closed. How can I close this filestream and delete the file in my 'Cancel' action?

--

OH! I found a method to resolve it now.

using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))

It is to simple, just declaration a fileshare property: FileShare.Delete

using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write, FileShare.Delete))

I spent 4 hours to google and debug and test and try to resolve it. Just 10 mins after I asked stackoverflow, I got the answer by myself. Interesting! And hope it is useful to someone too.


You could put that file stream in a session then use that session in your cancel action to close the stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号