0

I am trying to write a service which builds an .ics calendar file from string (which works) and send it to front-end. Front-end gets that file as a result of an api query. This is how it looks on my side:

var dataBytes = Encoding.ASCII.GetBytes(icsString);
var dataStream = new MemoryStream(dataBytes);

HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(dataStream) };
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "file.ics" };
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

return httpResponseMessage;

Is it correct? If it should work, then how to get the data in JS on the front-end side?

1 Answer 1

1

Your code looks fine, you need to close the fileStream and set responseStream Position to 0. You can refer to my code. and please make sure that file is present at the path and you are handling the exception

      //Copy the source file stream to MemoryStream and close the file stream
      MemoryStream responseStream = new MemoryStream();
      Stream fileStream = System.IO.File.Open(downloadFilePath, FileMode.Open);

      fileStream.CopyTo(responseStream);
      fileStream.Close();
      responseStream.Position = 0;

      HttpResponseMessage response = new HttpResponseMessage();
      response.StatusCode = HttpStatusCode.OK;

      //Write the memory stream to HttpResponseMessage content
      response.Content = new StreamContent(responseStream);
      string contentDisposition = string.Concat("attachment; filename=", fileName);
      response.Content.Headers.ContentDisposition = 
                    ContentDispositionHeaderValue.Parse(contentDisposition);
      return response;
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, I don't use FileStream - I want to send a string as a file. So what I do is create ByteArray from string and put it to MemoryStream. I positioned MemoryStream to 0 but it didn't help. HttpResponseMessage at the end has length like 324. Does it mean it is attached correctly and the front-end part is just reading it wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.