How to delete file after download

Asked by At

I want to create a response with a stream of a file in my api controller. After the action is finished, I want to delete the file.

        FileInfo fileInfo = null;
        var streamCopy = new MemoryStream();

            fileInfo = this.myService.CreateExcelExportFile(exportModel, temporaryImageDirectory);

            using (var streamIn = fileInfo.OpenRead())
                await streamIn.CopyToAsync(streamCopy);
        catch (Exception ex)
            throw new DomainException("");

        var result = this.Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(streamCopy);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;

In this scenario I'd always end up with a zero bytes file. I suspect this is because the memorystream streamCopy is beeing disposed before the response has been actually delivered. But in order to delete the file, I have to create a copy of the data, close the initial StreamReader and then delete the file. I know I mustn't close the StreamReader where result.Content = new StreamContent(streamCopy); depends on in the controller because of disposing. How do I solve this issue?

0 Answers