简体   繁体   中英

How to deal with temporary files in ASP.NET?

Note that I'm not talking about the compiler-generated "Temporary ASP.NET Files".

My web application (ASP.NET MVC) uses Graphviz to generate images that are then fed to the client. This requires the creation of temporary files.

What's the best way to deal with these? Is there a way to delete them immediately after they're sent? Should I use a background thread? Something in Application_Start or Application_End?

Graphviz creates the client, and adds them as a link in the page. so you cannot delete them directly.

there are several ways:

  • on application start, noone should use one of these images. so you can delete it
  • you add a reference to the image (eg the path) to the cache, and add a CacheItemRemovedCallback, that will delete your image. (limits nicely the amount of images on your HD
  • make a timer, that deletes the items periodically

be aware, that you should not delete the images, that are created just a second ago. due to they can be used.

你不能通过控制器或使用ASHX( http://www.marklio.com/marklio/CommentView,guid,df8d6471-83fd-4f66-a799-ef8274979f0e.aspx )流出内容并删除完成写出流后的临时文件?

使用其他用户描述的方法但是如果想要图像再次通过在响应中设置Last-Modifed标头然后在图像处理程序中获得If-Modified-Since标头,则要求浏览器使用其缓存,处理程序应该回复使用StatusCode 304“NOT Modified”,只要客户端浏览器尚未清除其缓存,图像仍会显示。

I like to deal with temporary files created by an action in the same action that generates them. For instance: (in MVC, but this could apply to any framework)

public ActionResult Foo()
{
    FooCleanup(); // deletes files in "~/temp/Foo/" older than a day or so

    string filename = CreateTemporaryFile(); // Creates a temporary file like "~/temp/Foo/{timestamp}.foo"
    return File(filename);
}

If Foo() gets called a lot, you can add some logic to only call cleanup every so often. This is kind of like a poor man's cron job, but it works well.

You could create an handler (.ashx) and stream the temp-file through that. That way you will know that the file has been transfered to the client, and you can delete the temp-file in the end of the handler.

A possible problem with this is that the client won't be able to download the file twice, since you're deleting it immediately. (Which could then be mitigated using the page-output cache...)

Though the best thing would be if you could avoid the temp-file problem all over , and stream out the file on request, by generating it in the handler...

我们使用带有计时器类型的application_start以每24小时的间隔运行,并每天清理/删除临时文件文件夹一次。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM