user1447679
user1447679

Reputation: 3230

How do you delete a file generated via webapi after returning the file as response?

I'm creating a file on the fly on a WebAPI call, and sending that file back to the client.

I think I'm misunderstanding flush/close on a FileStream:

Dim path As String = tempFolder & "\" & fileName
Dim result As New HttpResponseMessage(HttpStatusCode.OK)
Dim stream As New FileStream(path, FileMode.Open)
With result
    .Content = New StreamContent(stream)
    .Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
    .Content.Headers.ContentDisposition.FileName = fileName
    .Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/octet-stream")
    .Content.Headers.ContentLength = stream.Length
End With

'stream.Flush()
'stream.Close()
'Directory.Delete(tempFolder, True)

Return result

You can see where I've commented things out above.

Questions:

  1. Does the stream flush/close itself?
  2. How can I delete the tempFolder after returning the result?

On top of all this, it would be great to know how to generate the file and send it to the user without writing it to the file system first. I'm confident this is possible, but I'm not sure how. I'd love to be able to understand how to do this, and solve my current problem.

Update:

I went ahead with accepted answer, and found it to be quite simple:

Dim ReturnStream As MemoryStream = New MemoryStream()
Dim WriteStream As StreamWriter = New StreamWriter(ReturnStream)
With WriteStream
    .WriteLine("...")
End With
WriteStream.Flush()
WriteStream.Close()

Dim byteArray As Byte() = ReturnStream.ToArray()
ReturnStream.Flush()
ReturnStream.Close()

Then I was able to stream the content as bytearraycontent:

With result
    .Content = New ByteArrayContent(byteArray)
...
End With

Upvotes: 0

Views: 315

Answers (1)

Arin
Arin

Reputation: 1393

On top of all this, it would be great to know how to generate the file and send it to the user without writing it to the file system first. I'm confident this is possible, but I'm not sure how. I'd love to be able to understand how to do this, and solve my current problem.

To do the same thing without writing a file to disk, you might look into the MemoryStream class. As you'd guess, it streams data from memory like the FileStream does from a file. The two main steps would be:

  1. Take your object in memory and instead of writing it to a file, you'd serialize it into a MemoryStream using a BinaryFormatter or other method (see that topic on another StackOverflow Q here: How to convert an object to a byte array in C#).
  2. Pass the MemoryStream to the StreamContent method, exactly the same way you're passing the FileStream now.

Upvotes: 3

Related Questions