Reputation: 4863
On my site I have a list of previous order that a customer has placed that can each be viewed. I'm trying to allow the user to download a file that gives the details of each order, so that when they click "Download" on the order page, they will receive a file with the order details. I have the code to create the file, but I don't know how to serve it. Here's what I have so far:
var csv = new StringBuilder();
csv.Append("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date,Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier,Notes,Purchase Order");
foreach (var cartLine in model.Lines) {
var newLine = string.Format(.....)
csv.AppendLine(newLine);
}
System.IO.File.AppendAllText(filepath, csv.ToString());
So I have my file floating on the server, but what do I do with it? I also don't want these files to hang around forever taking up space, I'd like them to be deleted from the server as soon as they client receives them.
EDIT: I'm using MVC
Upvotes: 0
Views: 135
Reputation: 706
Provided you are using default asp.net stack (Controller/ApiController), do this by returning HttpResponseMessage
. Get stream from your csv string or whatever, set Content
property to your stream; change content-type header accordingly and you you're done.
Example:
public HttpResponseMessage GetCsv()
{
var csv = "whatever goes here";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(csv));
var message = new HttpResponseMessage()
{
Content = new StreamContent(stream)
};
message.Headers.Add("Content-type", "text/csv");
return message;
}
Upvotes: 0
Reputation: 885
You can just return the file as a stream from memory. You do not need to save it on the server's file system. Can you give more context on what kind of server technology do you use so that I can give you specific code. In MVC you can do it the following way:
var bytes = Encoding.UTF8.GetBytes(csv.ToString());
return this.File(bytes, "text/csv")
Return File takes content as byte array or stream and media type to tell the browser what kind of file you are returning.
Upvotes: 4