Bhanu Gotluru
Bhanu Gotluru

Reputation: 235

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.

Upvotes: 20

Views: 7788

Answers (3)

SergeyS
SergeyS

Reputation: 4510

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)
    )
};

Upvotes: 17

UnionP
UnionP

Reputation: 1638

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;

Upvotes: 4

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102398

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);
    }
}

Upvotes: 15

Related Questions