Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the file that was sent as StreamContent of HttpResponseMessage

In ASP.NET webapi, I send a temporary file to client. I open a stream to read the file and use the StreamContent on the HttpResponseMessage. Once the client receives the file, I want to delete this temporary file (without any other call from the client) Once the client recieves the file, the Dispose method of HttpResponseMessage is called & the stream is also disposed. Now, I want to delete the temporary file as well, at this point.

One way to do it is to derive a class from HttpResponseMessage class, override the Dispose method, delete this file & call the base class's dispose method. (I haven't tried it yet, so don't know if this works for sure)

I want to know if there is any better way to achieve this.

like image 226
Bhanu Gotluru Avatar asked Mar 08 '13 07:03

Bhanu Gotluru


3 Answers

Actually your comment helped solve the question... I wrote about it here:

Delete temporary file sent through a StreamContent in ASP.NET Web API HttpResponseMessage

Here's what worked for me. Note that the order of the calls inside Dispose differs from your comment:

public class FileHttpResponseMessage : HttpResponseMessage
{
    private string filePath;

    public FileHttpResponseMessage(string filePath)
    {
        this.filePath = filePath;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        Content.Dispose();

        File.Delete(filePath);
    }
}
like image 63
Leniel Maccaferri Avatar answered Nov 18 '22 08:11

Leniel Maccaferri


Create your StreamContent from a FileStream having DeleteOnClose option.

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StreamContent(
        new FileStream("myFile.txt", FileMode.Open, 
              FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose)
    )
};
like image 43
SergeyS Avatar answered Nov 18 '22 07:11

SergeyS


I did it by reading the file into a byte[] first, deleting the file, then returning the response:

        // Read the file into a byte[] so we can delete it before responding
        byte[] bytes;
        using (var stream = new FileStream(path, FileMode.Open))
        {
            bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
        }
        File.Delete(path);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(bytes);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.Add("content-disposition", "attachment; filename=foo.bar");
        return result;
like image 21
UnionP Avatar answered Nov 18 '22 06:11

UnionP