Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultipartFormDataStreamProvider Cleanup

Tags:

asp.net

If files are posted to my webapp, then I read them via MultipartFormDataStreamProvider.FileData.

I Initialize the provider like this:

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

And the provider nicely stores them as "~App_Data/BodyPart_{someguid}" But how do I clean up those files after I'm done with them?

like image 698
ldx Avatar asked Aug 22 '14 09:08

ldx


2 Answers

I know this question is old, but the best way I found to delete the temporary file was after processing it.

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

foreach (var file in provider.Files)
{
    // process file upload...

    // delete temporary file
    System.IO.File.Delete(file.LocalFileName);
}
like image 136
meany Avatar answered Nov 20 '22 19:11

meany


You could delete all files that are older than a certain timespan. e.g.

private void CleanTempFiles(string dir, int ageInMinutes)
{
    string[] files = Directory.GetFiles(dir);

    foreach (string file in files)
    {
        var time = File.GetCreationTime(file);

        if (time.AddMinutes(ageInMinutes) < DateTime.Now)
        {
            File.Delete(file);
        }
    }
}

Then call it with something like:

CleanTempFiles(root, 60); // Delete all files older than 1 hour
like image 25
Lee Gunn Avatar answered Nov 20 '22 21:11

Lee Gunn