Bhanu Gotluru Bhanu Gotluru - 2 months ago 24
ASP.NET (C#) Question

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.

Answer

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