0

I need to implement download button in my View and when user click i need to read some records from database create a file and download.

var stream = new MemoryStream();
stream.Position = 0;

var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
return response;

This is the code that I have for now, but I don't know how to write some data to it and how to convert to txt file.

Do i need to create it before and store on the server and here just to read it?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
usesser
  • 191
  • 3
  • 21

1 Answers1

0

You need to create your txt file before return from api. You can look here how to create a txt file.

This is your method which is return the stream.

var path = @"C:\YourFile.txt";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = 
    new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);   
result.Content.Headers.ContentLength = stream.Length;
return result;
Community
  • 1
  • 1
Must.Tek
  • 1,220
  • 10
  • 17